- Home /
GameObject.Find(string) cannot be accessed with an instance reference
qualify it with a type name instead. Whats the problem here? Line 12
using UnityEngine;
using System.Collections;
public class PowerUpScript : MonoBehaviour {
HUDScript hud;
private string mainCamera = "MainCamera";
void OnTriggerEnter(Collider2D other)
{
if (other.tag == "Player")
{
hud = gameObject.Find(mainCamera).GetComponent<HUDScript>();
hud.IncreaseScore(100);
Destroy(this.gameObject);
}
}
}
hud = gameObject.Find("mainCamera").GetComponent();
You need to put quotes around things that are strings. "Find" requires a string input.
Also, you should just call that line in void Start(){}, so that you don't create that large overhead every time you enter the collider... Find() is an expensive operation, and you only need to find the reference once, at the start of your scene.
The variable mainCamera is of type string though. So no need to put quotes around it.
Oh you're right, my eyes passed by that variable, I'm not sure why he created a variable for the name of the camera, was not expecting that haha
Answer by GameVortex · Jan 23, 2014 at 09:27 AM
The function **Find** is a static member of the class GameObject, which means that you have to access it using the type instead of the instance:
hud = GameObject.Find(mainCamera).GetComponent<HUDScript>(); //Notice the upper case G in GameObject to specify the class instead of the instance.
You appear to be searching for the MainCamera though and as long as your main camera is tagged as MainCamera you can easily access it through the Camera class instead:
hud = Camera.main.GetComponent<HUDScript>();
And as @Invertex says, you should put that code in a Start() of your script to avoid running it multiple times which is unnecessary .
this is the answer, and the tip to set HUDScript at the Start would help, also, you could have if(hud == null) hud = Camera.main.GetComponent();, just in case.
Hey I'm having a similar problem, and I was wondering if you'd be willing to help me out too GameVortex.
http://i.imgur.com/jI7C0n7.png
and
http://i.imgur.com/r$$anonymous$$zEiYf.png
are some screenshots of my code and stuff. Any help?