Hey everybody,
so I wrote a script, which creates two objects. In one of these object scripts, it want to get the objects SpriteRenderer component and it’s attached to!
But everytime I run the game it says NullReferenceException.
The line with the error is a comparison between the spriterenderer color of the objects, so I check first if one of them is null.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
public class LockDoor : MonoBehaviour {
public List<Color> colGen = new List<Color>();
public int colNow;
public int i;
public Transform doorsGO;
public Animation lockAnim;
public Controls controls;
public ScoreManagement scoreScript;
private new SpriteRenderer renderer;
void Awake()
{
// Find GameObejcts
doorsGO = GameObject.FindWithTag("doors").transform;
scoreScript = GameObject.Find("Score").GetComponent<ScoreManagement>();
//doorsGameObject = GameObject.Find("doors");
controls = doorsGO.GetComponent<Controls>();
}
// Use this for initialization
void Start () {
// GetComponents
lockAnim = GetComponent<Animation>();
lockAnim["LockTheDoor"].speed = 2.0f;
// Liste mit Farben
colGen.Add(Color.blue);
colGen.Add(Color.green);
colGen.Add(Color.yellow);
colGen.Add(Color.red);
// Change Color für Schlüssel
renderer = GetComponent<SpriteRenderer>();
colNow = Random.Range(0, colGen.Count);
renderer.color = colGen[colNow];
// Change Color für Türen
foreach (Transform colChi in doorsGO)
{
SpriteRenderer col = colChi.GetComponent<SpriteRenderer>();
i = Random.Range(0, colGen.Count);
col.color = colGen*;*
colGen.RemoveAt(i);
}
}
- IEnumerator WaitForAnimation () {*
lockAnim.Play();
controls.enabled = false;
scoreScript.enabled = true;
print(“You’ve locked the door!”);
yield return new WaitForSeconds(lockAnim.clip.length);
}
void OnTriggerEnter2D(Collider2D other)
{
SpriteRenderer othCol;
othCol = other.gameObject.GetComponent();
if (renderer != null)
{
if (renderer.color == othCol.color) // here is the line with the error
{
StartCoroutine(WaitForAnimation());
}
else
{
print(“Wrong door!”);
}
}
}
}
Thanks and sorry for my bad english!