vendredi 30 octobre 2015

How to handle if/else scope issue for variables set in "if condition" (Destroying GameObject in C#)

I'm using Unity and making a program that makes spheres appear once an object is clicked and then I want to delete the spheres when it is clicked again.

The problem is that on the initial run through the spheres are not defined since they are only created if the object is has not been clicked (!isSelected). I create them as an array of GameObjects but when I enter the else condition I receive the error NullReferenceException: Object Reference not set to an instance of an object Cube.OnMouseDown( ). I think this is because I originally set GameObject[] Spheres = null in the beginning. How should I initialize this variable so that I don't receive this error?

Also in general what's the best practice for using a variable that is defined in an if statement and modified in an else statement?

using UnityEngine;
using System.Collections;
using System.Linq;

public class Cube : MonoBehaviour {

    bool isSelected = false;

    void OnMouseDown() {
        Renderer rend = GetComponent<Renderer>();
        GameObject[] Spheres = null;

        if (!isSelected) {
            isSelected = true;
            rend.material.color = Color.blue; //#588c7e
            Vector3[] vertices = GetComponent<MeshFilter>().mesh.vertices;
            Vector3[] verts = removeDuplicates(vertices);
            Spheres = drawSpheres(verts);
        } else {
            rend.material.color = Color.white;
            print("destroy verts");
            for (int i=0; i<Spheres.Length; i++) {
                Destroy(Spheres[i]);
            }
            isSelected = false;
        }

    }
   GameObject[] drawSpheres(Vector3[] verts) {
        GameObject[] Spheres = new GameObject[verts.Length];
        for (int i = 0; i < verts.Length; i++) {
            Spheres[i] = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            Spheres[i].transform.position = verts[i];
            Spheres[i].transform.localScale -= new Vector3(0.8F, 0.8F, 0.8F);
            Spheres[i].AddComponent<VertClicked>();
        }
        return Spheres;
    }

} 

NOTE: I removed the removeDuplicates(), Start() and Update() functions from this class as I didn't think they contributed to the question.

Aucun commentaire:

Enregistrer un commentaire