Hi all,
I’m trying to understand making prefabs and using them in other scripts. I’ve been eating my face in frustration. Here’s one question:
Why can I access pickup.name here, but not pickup.germinationTime?
In Seeds.cs:
public int quantity;
public string variety;
public int germinationTime;
…
col.gameObject.SendMessage("PickupObject", gameObject);
…
And in PlayerInventory.cs, the first line works, second doesn’t:
void PickupObject(GameObject pickup)
{
Debug.Log("Picked Up " + pickup.name);
Debug.Log("Germination Time is " + pickup.germinationTime);
‘pickup’ is a game object. If you view the the script reference page for GameObject you will see the list of variables and functions you can access from a game object. “name” is one of those variables. “germinationTime” is not. Your ‘germinationTime’ lives in a different component…your Seeds component. It is not part of a game object. It is a different class attached to the game object. When you drag and drop your Seeds script on a game object, you create an instance of the seeds class attached to the game object.
To get access use GetComponent(). So in your code you could do something like:
void PickupObject(GameObject pickup)
{
Debug.Log("Picked Up " + pickup.name);
Seeds seeds = GetComponent<Seeds>();
Debug.Log("Germination Time is " + seeds.germinationTime);
Debug.Log("Variety is " + seeds.variety);
}
Note GetComponent() gets the component from a specific game object. Used like it is used here, it gets it from the current game object (i.e. the one the script is attached to). For accessing other game objects see:
Accessing Other Game Objects