Question by
Xregion · Aug 23, 2017 at 11:20 PM ·
instantiatevariablevariablesinterfaceinstantiation
Setting a variable on instantiation, but when the object is enabled the variable is set back to default.
I've set up an item drop system to drop an item and give it an amount. For example, if bullets drop it will be one game object, but have a variable to tell it how many bullets the player will get when they pick it up. This is the class for dropping the item.`using UnityEngine;
public class ItemDrop : MonoBehaviour {
public static void DropItem (GameObject[] items, Vector3 position)
{
int itemToDrop = Random.Range(0, items.Length);
int amountToDrop = Random.Range(1, 11);
Instantiate(items[itemToDrop], position, Quaternion.identity);
items[itemToDrop].GetComponent<IDroppable>().SetDropAmount(amountToDrop);
}
}
This is the interface IDroppable
public interface IDroppable {
void SetDropAmount(int amountToDrop);
}
Here is an example item
public class AmmoPack : MonoBehaviour, IDroppable {
int amountOfBullets;
public void SetDropAmount(int amountToDrop)
{
amountOfBullets = amountToDrop;
}
So when I call the method SetDropAmount and print the amountOfBullets to the console it shows the correct number, but when I print the amountOfBullets in the OnEnable() function it shows 0.
Why is this happening and how can I fix it?
Comment