- Home /
C# variable Error Message CS0219 variable not assigned
Im getting the following warning message in unity:
CS0219: The variable 'instance' is assigned but its value is never used
I know this is just a warning and my script still works, but I'd like to fix the code if possible rather than get this warning. However, I'm not familiar with c# and this project is a one-off so learning it now is not an option.
I know I could probably use the variable elsewhere, but I dont need to use it again so adding in redundant code doesnt seem like a good idea. I also read that I could possibly use a property instead of the variable but not sure about this or if it would work in this context.
Code follows:
public GameObject Prefab_Quakegas;
void Start()
{
GameObject instance = Instantiate(Prefab_Quakegas, transform.position, transform.rotation) as GameObject;
}
Answer by rutter · May 28, 2012 at 05:30 AM
Instantiate returns a reference to the newly created object, which you're storing in instance
. This is really useful if you need that reference, but in some circumstances you won't, and in those cases you don't have to store it.
In this case, you're storing the reference but never using it, and the compiler is logging a warning. As you seem to have guessed, this particular warning will never directly interfere with the compilation or execution of your program.
Here, you're calling Instantiate() and storing the return value:
GameObject instance = Instantiate(Prefab_Quakegas, transform.position, transform.rotation) as GameObject;
If you're never going to use that reference, you can just call Instantiate() and ignore the return value:
Instantiate(Prefab_Quakegas, transform.position, transform.rotation)
$$anonymous$$uch more thorough an answer than $$anonymous$$e. +1
Answer by Datael · May 28, 2012 at 05:21 AM
You just need to remove the assignment; change it to this:
public GameObject Prefab_Quakegas;
void Start()
{
Instantiate(Prefab_Quakegas, transform.position, transform.rotation) as GameObject;
}
Thanks for the suggestion. The suggested code above as is doesnt work, but if 'as GameObj' is removed from the end it will.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Can't figure out where to put 'new' when using c# 1 Answer
Distribute terrain in zones 3 Answers
can't read updated variable 2 Answers
Call a method whenever the assigned variable gets altered 2 Answers