- Home /
Unity Object not set to an instance
Hi I get keep this same error and I m not sure why. It keeps happening on my getComponent(). SceneManager sceneManager;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "asteroid")
{
Vector3 temp = other.transform.position;
temp.y = 8;
temp.x = Random.Range(-7.0f,7.0f);
other.transform.position = temp;
Destroy(gameObject);
sceneManager.GetComponent<SceneManager>();
sceneManager.AddScore();
}
}
Here is my SceneManager script
int score = 0;
// Update is called once per frame
void Update ()
{
print ("Your score is: " + score);
}
public void AddScore()
{
score += 50;
}
Answer by ankush_Kushwaha · Feb 09, 2014 at 04:02 PM
You can use GetComponet()
only with game objects not with class or scripts directly . First add an empty game object in your scene and attach your sceneManager
script with that empty game object. Then take a reference of that empty object in your OnTriggerEnter
script and use GetComponent()
.
I have the best alternative for you. You can use static function . Replace your
public void AddScore()
{
score += 50;
}
with
public static void AddScore()
{
score += 50;
}
and your
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "asteroid")
{
Vector3 temp = other.transform.position;
temp.y = 8;
temp.x = Random.Range(-7.0f,7.0f);
other.transform.position = temp;
Destroy(gameObject);
sceneManager.GetComponent<SceneManager>();
sceneManager.AddScore();
}
}
with
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "asteroid")
{
Vector3 temp = other.transform.position;
temp.y = 8;
temp.x = Random.Range(-7.0f,7.0f);
other.transform.position = temp;
Destroy(gameObject);
sceneManager.AddScore();
}
}
Answer by Murkas · Feb 09, 2014 at 03:41 PM
You want to assign sceneManager with GetComponent, thats the false way. You have to attach the sceneManager-Script to any GameObject and call GetComponent on a reference to this gameObject.
You should have a look on the Unity Video Tutorial.
Your answer
![](https://koobas.hobune.stream/wayback/20220613133003im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How getting transform of another GameObject C#? 1 Answer
Getcomponent what do i wrong? 2 Answers
how to disable/enable a script in c#? 2 Answers