Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Spawn GameObject when the player touches an obstacle

Discussion in 'Scripting' started by ziqibrandonli, Dec 31, 2020.

  1. ziqibrandonli

    ziqibrandonli

    Joined:
    Nov 21, 2020
    Posts:
    3
    I have followed the brackeys tutorial on breaking an object. He uses Instantiate to spawn the Cracked version of the object and destroys the original version.
    What I am doing is similar, when the player touches the obstacle, I want the obstacle to break.
    There are many obstacles in my scene, do I have to create a script for every single one? That is a lot of work. I'm sure there is another way to do it.
    I already have the cracked version of the obstacle(prefab). Also, I want to create a method and be able to call it in other scripts and I only want the obstacle that the player touches to break.
    Thank you:)
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    Nope. Just create one script, and put it on all of the breakable objects. Better yet, turn the breakable object itself into a prefab, and simply place instances of the prefab around your scene.
     
  3. ziqibrandonli

    ziqibrandonli

    Joined:
    Nov 21, 2020
    Posts:
    3
    If so, how do I specify which object I want to break when I call the method?:)
     
  4. payalzariya07

    payalzariya07

    Joined:
    Oct 5, 2018
    Posts:
    85
    Add gameobject tag and call On collision method
     
  5. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    You'll be inside the OnCollisionEnter or OnTriggerEnter method of the particular object that will be breaking. So it will just be "this".
     
  6. ziqibrandonli

    ziqibrandonli

    Joined:
    Nov 21, 2020
    Posts:
    3
    Thank you guys, my problem is solved;)