Now that we have our variables set up in GameBehavior, we can update Items every time we collect an Item in the scene, as follows:
- Add the following code to ItemBehavior:
public class ItemBehavior : MonoBehaviour
{
// 1
public GameBehavior gameManager;
void Start()
{
// 2
gameManager = GameObject.Find("Game
Manager").GetComponent<GameBehavior>();
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == "Player")
{
Destroy(this.transform.parent.gameObject);
Debug.Log("Item collected!");
// 3
gameManager.Items += 1;
}
}
}
- Hit Play and collect the pickup item to see the new console log print out from the manager script, as illustrated in the following screenshot:
Let's break down the code, as follows...