Due 24 Oct 2017
GetComponent
and the concepts we covered in class to get your GameObjects and Components to talk to each other and interactThe recording of my prototyping stream is available for your review if it helps
The cheat sheet has been ported to C# and is yours to study
The dot symbol .
shows up a lot. Microsoft calls it the "member access" operator, and their technical documentation might be helpful, but here's how I think about it: a.b
means get the thing named b
out of the thing named a
. a.b.c
means get the thing named b
out of the thing named a
, then get the thing named c
out of that thing. I say thing here because it can be objects, classes, namespaces, or methods.
Debug.Log("Hello");
Get the Log
method out of the Debug
class and call it with the string "Hello"
gameObject.transform.Translate(1, 3, 4);
Get the Translate
method out of the transform
object out of the gameObject
object the current script is attached to and call it with the parameters 1, 3, 4
.
When we called GetComponent
in class, the syntax looks a bit different from other methods
GetComponent<Rigidbody>().AddForce(1, 0, 0);
GetComponent
here is what C# calls a generic method. Unity and Microsoft have their own documentation if that helps. That means it's a method that knows something extra about the type of data it is operating on, in this case the type of component it is returning. You put the type information between angle brackets before the parentheses. Other than that, it's like calling a normal method. Generics are what allow MonoDevelop to display auto completion for you. There are other ways of calling GetComponent
without the angle brackets
GetComponent("Rigidbody");
GetComponent(typeof(Rigidbody));
But C# does not actually know the exact kind of component that will be returned, so you cannot do this:
GetComponent("Rigidbody").AddForce(1, 0, 0); // does not work
GetComponent(typeof(Rigidbody)).AddForce(1, 0, 0); // does not work
Instead, you have to cast the value, basically tell C# that you're sure you will get a Rigidbody
object
((Rigidbody)GetComponent("Rigidbody")).AddForce(1, 0, 0); // does will work
((Rigidbody)GetComponent(typeof(Rigidbody))).AddForce(1, 0, 0); // does will work
This is pretty clunky, and does not get auto completion, so I prefer generics.