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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Getting an Object to Move After Touching Another Object

Discussion in 'Scripting' started by Dev_23, Aug 5, 2015.

  1. Dev_23

    Dev_23

    Joined:
    Oct 4, 2014
    Posts:
    18
    I want to get my player to move to the beginning of level when it touches a trigger collider (called LevelEnd). I'm not quite sure if I should put the script in the LevelEnd object or my player object or how to do it. I'm using C++. Any help would be appreciated!
     
    Last edited: Aug 5, 2015
  2. sz-Bit-Barons

    sz-Bit-Barons

    Joined:
    Nov 12, 2013
    Posts:
    150
    I probably would solve it like this:
    The LevelEnd Object has a Command Container Object, which has a command defined (in this case "move to the beginning of level").
    When the player touches the LevelEnd Object, the LevelEnd Object passes that command to the player and the player executes it.

    (However, I use the plugin FullInspector excessively, so maybe this approach is not really usable without full inspector)
     
  3. tedthebug

    tedthebug

    Joined:
    May 6, 2015
    Posts:
    2,570
    You can have the event on the player or on the end object. Just set a trigger so that when the player hits the object the trigger is detected & sends the player off.
    Personally I put the script on the object & make the new spawn point, if it's on the same unity scene, a public game object so I can drag it onto the object in the inspector. I make the collider on the end object the trigger then ontriggerenter I transform.position the player to (spawnpoint.position). If it's to a new unity scene then ontriggerenter triggers application.loadsceen(x)

    By putting the script on the end object my player isn't carrying around a whole bunch of stuff if it can't be reused. Of course, if you are storing the level on playerprefs or something then you could get it back & then use it as the scene (application.loadscene(current level+1))
     
    Dev_23 likes this.
  4. Dev_23

    Dev_23

    Joined:
    Oct 4, 2014
    Posts:
    18
    How do I get a reference to the player? I have this:

    Code (CSharp):
    1.     void onTriggerEnter() {
    2.         Transform.position =
    3.     }
     
  5. tedthebug

    tedthebug

    Joined:
    May 6, 2015
    Posts:
    2,570
    Don't have a PC here but it's something like

    void OnTriggerEnter (Collider other){
    other.gameObject.transform.position =

    }

    This is assuming the player is the only thing that can collide with the end object.