Reputation: 41
So some important things to let you guys know is this is in unity and this script is on a gameObject(the key). It casts a ray and then with
hitinfo.transform.SendMessage("interactedWithItem");
this function below is called from another script. I can state that the Debug.Log("this is a key")
is triggerd and shows in console, but for what ever reason the value of keyAmount isn't incremented. What am I doing wrong?
public int keyAmount;
public bool storableItem = true;
bool key = true;
//The function that will run if the storable item is set to true
public void interactedWithItem()
{
//Checks if the object is a key
if (key)
{
keyAmount++;
Debug.Log("is a key");
}
gameObject.SetActive(false);
}
Upvotes: 2
Views: 699
Reputation: 3455
I think your script is instanciated when it is called. Because of this your variables are reset. Try this example:
public class MyClass
{
static void Main(string[] args)
{
MyClass myObject = new MyClass();
myObject.Increase();
myObject.Print(); // output: 1, 1
myObject = new MyClass(); // new instance => only static variables are stored in the class and will not be dismissed.
myObject.Increase();
myObject.Print(); // output 1, 2
}
private int NotStaticItem = 0; // one per instance/object
private static int StaticItem = 0; // one per class
public void Increase()
{
NotStaticItem++;
StaticItem++;
}
public void Print()
{
Console.WriteLine("NotStaticItem: {0}", NotStaticItem);
Console.WriteLine("StaticItem: {0}", StaticItem);
}
}
Build two KeyCounts. One static and one not-static. If the static value is not being reset you know, that unity builds new objects in this case.
Upvotes: 2