In: Computer Science
View the following C# Script carefully. Assume that the Script is enabled, is attached to an active GameObject, and addresses the appropriate namespaces first.
1 public class Player : MonoBehaviour
2 {
3 public GameObject coinPrefab;
4 private GameObject coin;
5 public Transform spawnpoint;
6
7 void Update()
8 {
9 if
(Input.GetMouseButtonDown(0))
10 {
11
Instantiate(coinPrefab, spawnpoint.position,
spawnpoint.rotation);
12 }
13 if
(Input.GetMouseButtonDown(1))
14 {
15 coin
= GameObject.FindWithTag("Coin");
16
Destroy(coin);
17 }
18 }
19 }
the Update() function is called once for each frame. We use Time.deltaTime to calculate time difference between 2 update calls
I've added comments above each line for explanation
1 public class Player : MonoBehaviour
2 {
3 public GameObject coinPrefab;
4 private GameObject coin;
5 public Transform spawnpoint;
6
7 void Update()
8 {
//if primary button of mouse is pressed (primary button is left
click)
9 if (Input.GetMouseButtonDown(0))
10 {
// create a clone of coinPrefab at specific
position(spawnpoint.position) and specific
angle(spawnpoint.rotation)
11 Instantiate(coinPrefab, spawnpoint.position,
spawnpoint.rotation);
12 }
//if secondary mouse button is pressed (right click)
13 if (Input.GetMouseButtonDown(1))
14 {
// returns a game object which is tagged "Coin" and store it in
variable coin. If none found, it returns null
15 coin = GameObject.FindWithTag("Coin");
//Destroy the coin object retrieved in previous line
16 Destroy(coin);
17 }
18 }
19 }