- Home /
The question is answered, right answer was accepted
Very, very strange float assignment problem.
Hello. I've currently got an utterly baffling problem with assigning variables in one of my scripts. Basically, the value I'm assigning is completely different from the one being used in the game. The script below holds data for weapons, and is very simple. Code:
using UnityEngine;
using System.Collections;
public class WeaponStats : MonoBehaviour {
WeaponEquip weaponEquip;
//Scimitar
[HideInInspector]public float scim_one_speed = 4.0f;
[HideInInspector]public int scim_one_damage = 50;
//Dagger
[HideInInspector]public float dagger_one_speed = 0.0f;
[HideInInspector]public int dagger_one_damage = 34;
void Start () {
Debug.Log (scim_one_speed);
Debug.Log (dagger_one_speed);
}
}
You'd expect the console to print off '4.0' and '0.0' as those two variables. Nope. The strangest part is that the console doesn't just print off two incorrect values, it prints off four. According to Unity, 'scim_one_speed' is simultaneously '1' and '0', while 'dagger_one_speed' is simultaneously '0.75' and '0' at run-time. If anyone has any idea why this is happening, I'd be very grateful for their help.
Do you have any other script that access to these variables? Since they are public, they are pretty much accessible. Try making them private and see if they works. Secondly, assign values in Awake function ins$$anonymous$$d of at the instantiation.
[SOLVED] $$anonymous$$an, I hate how I usually find the answer right after I post a UnityAnswers query. I guess the problem was that since the variables were public and serialized, they were saving some value (the "1","0.75","0","1") from somewhere. Adding the '[System.NonSerialized]" attribute fixed the issue. I'm not entirely sure if I should post this as an answer, so I'll just keep it as a comment for now. Thanks anyways, guys. [EDIT] This is a needless solution. The reason I needed to add this attribute is answered by Eric5h5 below.
Answer by Eric5h5 · May 23, 2014 at 10:43 PM
You attached the script to two different objects, and the variables hold the values that Unity is printing. If it says that scim_one_speed is 1, then it is. Since they're public, the values do not come from your code, aside from the initial assignment, they come from the inspector. If you remove the HideInInspectors you can see what the values actually are.
So I guess I sort of had half the right answer. Non-serialization fixed it because I had two copies on my GameObject that I didn't notice. So, yeah, you're right. Thanks.
Answer by Jeff-Kesselman · May 23, 2014 at 10:42 PM
You probably have two copies of this component out there.
Either they are both on the same GameObject, or you have one a piece on multiple game objects. Its ALSO possible that you have the same basic code in two different script files.
Fix that first so there is only one and it really is this current component. Then attack the values if there is still an issue.