Beginner Questions

I’m studying C# and Unity for the first time. I have some beginner questions:

In this code line, how are they using <> brackets instead of ()? There is another file called PlayerScript.cs. So I think that means that it created a “class” PlayerScript and that is why they can declare myPlayerScript and refer to it here this way.

PlayerScript myPlayerScript;

    void Awake()
    {
        myPlayerScript = transform.parent.GetComponent<PlayerScript>();
    }

Also, how does it know what parents of what transform this is referring to? Does it depend on what GameObject (like, literally what thing in the hierarchy) you drag this script onto in the Unity editor?

Thank you

The angle brackets denote that you’re calling the “generic” version of the GetComponent method. Within the angle brackets, you specify the type (datatype) of component you’re trying to get. If you look at the scripting docs, you’ll see that there is also a non-generic version of GetComponent(). Generics just allow for cleaner / simpler coding in many situations.

So, basically that line is saying:

  • Get the transform of the current object (the object this script is attached to), then get the parent object of that transform (so the parent of this object), then get the PlayerScript component that’s attached to said parent.

It all depends on what object the running script is attached to. That object’s Transform component is what’s being referenced by “transform” in the above script.

Jeff

Ok thanks.

Also, I see examples where the OnTriggerEnter() method has OnTriggerEnter(Collider other) … most of the time, but once I saw it say

void OnTriggerEnter(Collider theCollision) {
}

And I can’t find “theCollision” defined or declared anywhere in the project!? And I see “other” in the documentation, in the page about the OnTriggerEnter() method, but what is this arbitrary component ‘other’?

Yeah, so both of your examples are simply method calls. Every time Unity calls an OnTriggerEnter() method, it pass exactly one argument into that method. That argument is a Collider component. Hence both of your examples start out “OnTriggerEnter(Collider”. Now, the next token is just an arbitrary name that you can refer to the passed collider as within the OnTriggerEnter() method.

So, your examples could have looked like this:

void OnTriggerEnter(Collider foo)
{
  // now, you can reference the passed collider as "foo"
}

So, it’s just a local name for the passed argument and can be anything you decide (as long as it’s legal in C#).

Jeff

hmmmm okay.

You might want to take a look at some basic C# tutorials on the internet - there are plenty of them. Or, you could look at the more Unity-centric ones provided by Unity.

http://unity3d.com/learn/tutorials/modules/beginner/scripting

Jeff