- Home /
GameObject.Find either can't be called or is in the wrong scope.
I'm trying to make infinite terrain and for this, I'm instantiating one gameobject of my ground and destroying another when a collision occurs. Since the ground will be destroyed and created at runtime, I can't assign it from the inspector because it won't work after the first object is destroyed. I used GameObject.Find to do this but I run into two issues. Here is the first thing I did:
public class trigger : MonoBehaviour
{
public GameObject newterrain;
void Start()
{
newterrain = GameObject.Find("ground");
}
void Update()
{
}
void OnCollisionEnter()
{
Instantiate(newterrain, new Vector3(20f, 1.089f, -5.16f), Quaternion.identity);
}
}
And I get this error: "FindGameObjectWithTag is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'trigger'." However, when I call it in start, I can't use it in my OnCollisionEnter function because it's a local variable.
public class trigger : MonoBehaviour
{
void Start()
{
GameObject newterrain = GameObject.Find("ground");
}
void Update()
{
}
void OnCollisionEnter()
{
Instantiate(newterrain, new Vector3(20f, 1.089f, -5.16f), Quaternion.identity);
}
}
So is there a workaround to having to declare the variable in Start? Thanks for any help you're able to give.
Hello, First FindGameObjectWithTag is not allowed to be called from a $$anonymous$$onoBehaviour constructor (or instance field initializer), call it in Awake or Start instead" in that code you are not calling FindGameObjectWithTag so its imposible that error occurs there. The code you have posted has no relation at all with what you are trying to achieve, you are trying to find a gameobject called ground before its instantiated? it is hard to tell what you want to do