Search Unity

Variable is assigned but never used?

Discussion in 'Scripting' started by gRntaus, Feb 4, 2013.

  1. gRntaus

    gRntaus

    Joined:
    Jul 16, 2012
    Posts:
    27
    I've got a "warning" in my inspector saying that the variable "clone" is assigned but never used. The script is fairly simple (I'm iterating on it as I go) but essentially I've attached a public gameobject to the script which is the enemy prefab. I've been told never to work with the prefab directly and instead spawn another instance of the object so I can mess with it, destroy it do whatever and the prefab stays intact. As a result I decided to call my variable clone and instantiate it a varied number of times. Whenever I spawn an enemy there is a function that renames it to something unique so I can identify it so they aren't all called clone but I don't understand why it says the variable if never used is I'm spawning enemies with it.

    The code is below how can I alter this to make the code more elegant / get rid of the warning. Basically I just want to Instantiate copies of my enemy prefab x amount of times. The actual enemy object takes care of identifying itself when it's spawned so is there a way to do it without even linking it to a gameobject at all? Thanks!

    ERROR:
    Assets/Scripts/EnemySpawn.cs(10,28): warning CS0414: The private field `EnemySpawn.clone' is assigned but its value is never used


    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class EnemySpawn : MonoBehaviour {
    5.  
    6.     //Prefab associated with the script
    7.     public GameObject enemy;
    8.    
    9.     //Clone of prefab so we can work with it
    10.     private GameObject clone;
    11.    
    12.     //Tracks enemies spawned
    13.     private int enemycount = 0;
    14.    
    15.     //Spawn Location
    16.     private Vector3 spawnlocation = new Vector3(0,0,0);
    17.    
    18.     //Starts the Spawn co-routine
    19.     void Start () {
    20.         Spawn ();
    21.     }
    22.    
    23.     //Spawns a new enemy even half second until 10 enemies are on screen.
    24.     void Spawn () {
    25.             if (enemycount < 10) {
    26.             clone = Instantiate(enemy, spawnlocation, Quaternion.identity) as  GameObject;
    27.             enemycount++;
    28.             Invoke("Spawn", 0.5f);
    29.         }
    30.        
    31.     }
    32.     }
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    Instead of:

    Code (csharp):
    1.  
    2. clone = Instantiate(enemy, spawnlocation, Quaternion.identity) as  GameObject;
    3.  
    Code (csharp):
    1.  
    2. Instantiate (enemy, spawnlocation, Quaternion.identity);
    3.  
    And delete your clone variable to get rid of the warning.
     
    DragonOuali likes this.
  3. gRntaus

    gRntaus

    Joined:
    Jul 16, 2012
    Posts:
    27
    Thankyou good sir.