Problem when I call fonction with child class
Hello, i'm french but i think find more answers in this forum. Sorry if my english is bad. I try to call a parent fonction when an evenement "on trigger enterer" is coming in a child class. Child class :
public class PickUp : MonoBehaviour {
public Item item;
Inventory inventoryScript;
void OnTriggerEnter(Collider other)
{
inventoryScript.AddItem(item);
}
}
And my parent class :
public class Inventory : MonoBehaviour {
public const int nbSlots = 30;
public Item[] items = new Item[nbSlots];
public GameObject A1;
public void AddItem(Item itemToAdd)
{
for (int i = 0; i < items.Length; i++)
{
if (items[i] == null)
{
items[i] = itemToAdd;
A1.GetComponent<Image>().sprite = itemToAdd.sprite;
return;
}
}
}
}
My error appear in "PickUp" script at line 13 : inventoryScript.AddItem(item);
thank you in advance
Answer by HenryStrattonFW · Feb 28, 2017 at 08:49 PM
If your pasted scripts are all there is to your scripts, then this is because your Pickup script has no reference to the inventory script. it just has a variable that can hold a reference to one. You should either give that Inventory variable a [SerializeField] attribute, and link it in the inspector, or do something like this.
void OnTriggerEnter(Collider other)
{
if(inventoryScript == null)
{
// NOTE: this may need to change It was not clear to me from your initial post what the hierarchy was like
// so your Inventory component may not be directly on this items parent. This is just an example.
inventoryScript = transform.parent.GetComponent<Inventory>();
}
if(inventoryScript == null)
{
Debug.LogError("Failed to find Inventory component on parent");
}
else
{
inventoryScript.AddItem(item);
}
}
Your answer
Follow this Question
Related Questions
Script for activating next GameObject after first one has been found/tracked (Vuforia) 1 Answer
Prefab Scripts Not Working After First Spawn? 2 Answers
SOME slider don't accept SOME variables... WHY??? 0 Answers
Unity2d move enemy in opposite direction on collision 1 Answer
How to know the animator's bones 0 Answers