Search Unity

Randomise Instantiate on touch

Discussion in 'Scripting' started by Kiesco91, Apr 20, 2019.

  1. Kiesco91

    Kiesco91

    Joined:
    Aug 20, 2018
    Posts:
    80
    hello,

    im trying to make game objects instantiate on touch of android screen but I can't seem to work the code out. I have looked at other forum posts but I can't get it to work for me. I get error codes and in my script and I don't know what I need to do :(

    I basically want when I touch the screen, an object appears, waits for a second and then destroys itself.

    line 37 brings up 'Embedded statement cannot be a declaration or labeled statement'
    line 38 brings up 'the name 'prefabIndex' does not exist in the current context'

    I have tried these in the start function aswell but it doesn't work.

    Code (CSharp):
    1.  
    2. {
    3.  
    4.     List<GameObject> prefabList = new List<GameObject>();
    5.     public GameObject Prefab1;
    6.     public GameObject Prefab2;
    7.     public GameObject Prefab3;
    8.     public GameObject Prefab4;
    9.     public GameObject Prefab5;
    10.     public float time;
    11.  
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.         prefabList.Add(Prefab1);
    16.         prefabList.Add(Prefab2);
    17.         prefabList.Add(Prefab3);
    18.         prefabList.Add(Prefab4);
    19.         prefabList.Add(Prefab5);
    20.  
    21.     }
    22.  
    23.     // Update is called once per frame
    24.     void Update()
    25.     {
    26.         if (Input.touchCount > 0)
    27.         {
    28.             Touch touch = Input.GetTouch(0);
    29.             Vector2 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
    30.  
    31.             if (touch.phase == TouchPhase.Began)
    32.  
    33.                 int prefabIndex = UnityEngine.Random.Range(0, 5);
    34.             Instantiate(prefabList[prefabIndex]);
    35.  
    36.             {
    37.                 Destroy(gameObject, time);
    38.             }
    39.  
    40.         }
    41.     }
    42. }

    thanks,
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Your braces are out of whack, you have it at line 36 but you want it at line 32.

    You're also destroying the gameObject this is attached to, not the newly Instantiated clone.
     
  3. Kiesco91

    Kiesco91

    Joined:
    Aug 20, 2018
    Posts:
    80
    How would I go about destroying the clone and not the prefab? Sorry I'm not great at coding but trying to learn :(
     
  4. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Instantiate returns the object it creates, you want to use that in your Destroy() call.