4
\$\begingroup\$

I have been following along with a Lynda.com video course to familiarize with Unity. I am currently attempting to grab a reference to a scene's First Person Controller's transform as follows:

Transform targetObject;

// Use this for initialization
void Start ()
{
    targetObject = gameObject.Find("First Person Controller").transform;
}

And this is within a script/class that inherits from MonoBehaviour. However, this gives the error:

 Static member `UnityEngine.GameObject.Find(string)' cannot be accessed with an instance reference, qualify it with a type name instead

I am sure there is a way to just change the logic and get the desired affect with a different approach. But I do not understand why this results in an error. It is the same code used by the instructor of the course, and from the Unity Script Reference, I can see that MonoBehaviour inherits a gameObject member which has the Find() method. So this error is saying there is only one GameObject instance for all MonoBehaviour classes right? But shouldn't I still be able to call it's methods?

I am using Unity 4.1 with C# while the instructor is using 3.5 (with JS) if that helps any.

\$\endgroup\$
1
  • \$\begingroup\$ Yep, as Benjamin says, it's almost the same code the instructor uses. Just a capital G should sort you out. Remember to always read your error messages, "cannot be accessed with an instance reference, qualify it with a type name instead" is telling you exactly what's wrong and exactly how to fix it. \$\endgroup\$
    – House
    Commented Aug 5, 2013 at 17:52

2 Answers 2

9
\$\begingroup\$

You actually just made a simple typo. gameObject is the current GameObject that your script is attached to. GameObject is the type. The error message is saying that the Find(string) function only works when it is called on the type (GameObject) not an instance of the type (gameObject).

Simply put, use GameObject.Find("First Person Controller") instead of gameObject.Find("First Person Controller").

\$\endgroup\$
2
  • \$\begingroup\$ Ah, yeah I actually tried this shortly after posting and reading the error message more clearly. It fixed the error, but perhaps it was allowed in 3.5 or with js, because it definitely didn't raise an error for her. Thx for the response! \$\endgroup\$
    – Christian
    Commented Aug 5, 2013 at 18:18
  • \$\begingroup\$ JavaScript can be quite tricky and unpredictable at times. I believe it does allow you to use instances to access static methods which is a little unintuitive because the instance is not actually used. I highly suggest working with C# simply for its regularity. \$\endgroup\$ Commented Aug 5, 2013 at 19:54
-3
\$\begingroup\$

Transform targetObject;

// Use this for initialization
void Start ()
{
    targetObject = GameObject.Find("First Person Controller").GetComponent<Transform>();
}
\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .