Skip to content

Recipes and common patterns

Folcon edited this page Nov 5, 2021 · 9 revisions

Recipes

Some basic ideas, procedures, building blocks to empower and get the creative juices flowing. Maybe you're new to Arcadia and you just want to play around and wield the raw power of live-coding reality before digging deep into docs. Even when you're not new to Unity or Clojure, maybe Arcadia programming is a casual art-code activity, it can be challenging to dip back into the unique headspace of conjuring magical digital objects atop this crazy stack of turtles.

Spawn a cube 3 units in front of the MainCamera

(use 'arcadia.core 'arcadia.linear)

(let [cube (create-primitive :cube "Nice Cube")
      tr-cam (. Camera/main transform)]
  (set! (.. cube transform position)
        (v3+ (. tr-cam position) 
             (v3* (. tr-cam forward) 3))))

Spawn a prefab

Create a Resources folder inside your Assets and put your prefabs in there.

(import '[UnityEngine GameObject Resources])
(GameObject/Instantiate (Resources/Load "Path/To/Prefab/With/No/Extension"))

Remember don't use an .prefab extension with referencing the prefab.

Working with side-effecting Unity code

Use this when you have a Unity or other C# function that gives you a callback and returns void, it's an easy way to wrap that to convert it to a function that takes in an input and just returns an output. However be careful if the FuncCallThatReturnsVoid is async.

(let [things (fn-that-gives-things)
      thing-coll (atom [])]
  (.FuncCallThatReturnsVoid (wrapped-fn things)
    (fn [thing] (swap! thing-coll conj thing)))
  @thing-coll)

Converting Clojure Collections to C# collections

There will be times when you need to give Unity functions C# collections, in those instances knowing how to make collections like shown below will be useful. Use the Specifying Types segment of the clr wiki to help know what types will look like.

(defn coll->c#list [v]
  (let [xs (|System.Collections.Generic.List`1[System.String]|.)]
    (doseq [e v]
      (.Add xs e))
    xs))

Introspecting methods and properties of an instance

If you're at the REPL and have an instance of something and are trying to work out how to use it, try the snippet below. It provides a nicely readable table of output.

(require '[clojure.reflect :as r])
(r/reflect Thing)

(use '[clojure.pprint :only [print-table]])
(print-table (:members (r/reflect Thing)))

Patterns

It has been said that a poorly timed garbage collection can really disturb one's well-being in VR. With great power comes great responsibility to prevent VR sickness. That aside, Arcadia is a niche environment whose idioms are yet to be discovered. There are many ways to accomplish one's goals. Some are more legible but produce a ton of garbage.

Clone this wiki locally