MissingReferenceException what sshould I do?
i have a Problem with my Code. Ive implemented a bullet where i can shoot on Object. but if the Object is colliding with the other Object its showing "MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. ShootingController.Update () (at Assets/Scripts/ShootingController.cs:44)". What did i wrong?
public class ShootingController : MonoBehaviour {
public GameObject crosshairs;
private Vector3 target;
public GameObject player;
public GameObject bulletPrefab;
public GameObject bulletStart;
public float bulletSpeed = 60.0f;
public Text scoreText;
public int Score;
private GazeAware2D _gazeAware;
public GameObject gameOverPanel;
// Start is called before the first frame update
void Start()
{
Cursor.visible = false;
_gazeAware = GetComponent<GazeAware2D>();
}
// Update is called once per frame
void Update()
{
//_gazeAware = new Vector3(TobiiAPI.GetGazePoint().Screen.x, TobiiAPI.GetGazePoint().Screen.y, 0);
//target = transform.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z));
//crosshairs.transform.position = new Vector2(target.x, target.y);
target = transform.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(TobiiAPI.GetGazePoint().Screen.x, TobiiAPI.GetGazePoint().Screen.y, 0));
crosshairs.transform.position = new Vector2(target.x, target.y);
Vector3 difference = target - player.transform.position; // --> this one is the Script humber 44
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
player.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
//Input.GetKeyDown wird nur einmal wahr, wenn die angegebene Taste gedrückt wird
if (Input.GetKeyDown(KeyCode.Space))
{
float distance = difference.magnitude;
Vector2 direction = difference / distance;
direction.Normalize();
fireBullet(direction, rotationZ);
Debug.Log("Shooting a bullet");
}
}
void fireBullet(Vector2 direction, float rotationZ)
{
GameObject b = Instantiate(bulletPrefab) as GameObject;
b.transform.position = bulletStart.transform.position;
b.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
b.GetComponent<Rigidbody2D>().velocity = direction * bulletSpeed;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name.Contains("satellite") || collision.gameObject.name.Contains("moon") || collision.gameObject.name.Contains("ufo"))
{
Score++;
scoreText.text = Score.ToString();
}
}
}
Comment
Your answer
Follow this Question
Related Questions
[Unity2D] Adding Sound to a Prefab 0 Answers
How do I stop this script? 0 Answers
Prefab Direction - shooting 2 Answers
2d shooting,Shooting bullets 2d 0 Answers