- Home /
Object reference not set to an instance of an object
Hey, I am relatively new to Unity and am currently making a game that requires an object to change another object's variable when they collide. However, I have tried doing so but it doesn't seem to work and I keep getting the error 'Object reference not set to an instance of an object'. What am I doing wrong?
using UnityEngine;
using System.Collections;
public class Collision : MonoBehaviour {
string state = "";
Animator animator;
SpaceShip_Movement spaceship_script;
void Start(){
Vector3 pos = transform.position;
pos.y = Random.Range(-2.4f + 0.4748199f,-0.85f - 0.4748199f);
transform.position = pos;
animator = GetComponent<Animator>();
int decision = Random.Range(1, 8);
if(decision <= 5){
state = "flying_n";
animator.SetInteger("State", 4);
} else{
state = "flying_s";
animator.SetInteger("State", 5);
}
if (animator == null) {
Debug.LogError("Didn't find animator.");
}
if (renderer == null) {
Debug.LogError("Didn't find renderer.");
}
}
void FixedUpdate(){
Vector3 velocity = Vector3.zero;
velocity.x = -0.01f;
transform.position += velocity;
}
void OnTriggerEnter2D(Collider2D collider){
Debug.Log("Triggered:" + collider.tag);
if (collider.tag == "Player") {
if(spaceship_script.isBoosting == true){
switch (state) {
case "flying_n":
animator.SetInteger("State",1);
break;
case "flying_s":
int decision = Random.Range(1,4);
if(decision == 1 || decision == 2){
animator.SetInteger("State",2);
} else if (decision == 3){
animator.SetInteger("State",3);
}
break;
}
} else if (spaceship_script.health != 0){
spaceship_script.health -= 1;
}
}else if(collider.tag == "Looper") {
Vector3 pos = transform.position;
pos.y = Random.Range(-2.4f + 0.4748199f,-0.85f - 0.4748199f);
pos.x += 15;
int decision = Random.Range(1, 7);
if(decision <= 5){
state = "flying_n";
animator.SetInteger("State", 4);
} else{
state = "flying_s";
animator.SetInteger("State", 5);
}
transform.position = pos;
}
}
}
As far as i could tell, you didn't assign anything to the script type variable. (spaceship_script)
Very common problem/mistake. There are many answered questions here with the same title and pretty much the same solution. And many different ways of explaining what's really going on.
Your answer
![](https://koobas.hobune.stream/wayback/20220613160820im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
How do you access other Variables on other scripts c# 1 Answer
Multiple Cars not working 1 Answer
A node in a childnode? 1 Answer