- Home /
Why isn't the variable being assigned?
I'm using the unity debugger to find out why a variable isn't being changed. What I found was very strange.
The yellow mark is where the code execution currently is. So the variable hold should be assigned. The position 8,2,2 in map indeed holds a character object according to the debugger. However, hold which is assigned to map[8,2,2] does not have a reference to a character object, instead it has one to a null obj.
So my question is, why isn't the variable being assigned properly?
Edit:
You can see that there is an object at map[8,2,2] already. The problem is that hold isn't being assigned to the value at 8,2,2. Instead it is being assigned to a different Entity, which holds a reference to a null object.
Edit #2 (added code for Entity class)
using UnityEngine;
using System.Collections;
using Newtonsoft.Json;
[JsonObject(MemberSerialization.OptIn)]
public class Entity : System.IEquatable<Entity>
{
[JsonProperty]
public int x;
[JsonProperty]
public int y;
[JsonProperty]
public int z;
[JsonProperty]
public states type;
public GameObject obj;
public Entity()
{
obj = null;
this.type=states.empty;
}
public Entity(GameObject reference, states type)
{
obj = reference;
x = (int) obj.transform.position.x;
y = (int) obj.transform.position.y;
z = (int) obj.transform.position.z;
this.type = type;
}
public bool Equals(Entity other)
{
return this.x==other.x&&this.y==other.y
&&this.z==other.z&&this.type==other.type;
}
public string getCoordinatesasString()
{
return x.ToString()+','+y.ToString()+','+z.ToString()+','+type.ToString();
}
public Vector3 getCoordinates()
{
return new Vector3(x,y,z);
}
public void setData(int x, int y, int z, states type)
{
this.x=x;
this.y=y;
this.z=z;
this.type=type;
}
}
Answer by Tomer-Barkan · May 19, 2013 at 06:47 AM
Edit:
Oh! I don't know how I missed this earlier... You can't cast a float to an int using (int)someFloat
... it won't work!
You can use Mathf.RoundToInt(someFloat)
instead. Try it.
So change the assignment line to
Entity hold = map[Mathf.RoundToInt(position.x), Mathf.RoundToInt(position.y), Mathf.RoundToInt(position.z)];
The map isn't empty though, I attached some more screenshots to show this.
I should mention the default constructor for an Entity assigns a null obj
Oh! I don't know how I missed this earlier... don't cast a float to an int using (int)someFloat
... it doesn't always yield the result you expect!
You can use $$anonymous$$athf.RoundToInt(someFloat)
ins$$anonymous$$d. Try it.
I used RoundToInt ins$$anonymous$$d, and that fixed the problem! Though could you explain why it did? Shouldn't (int) cast it to an int?