Changing the code from collision to button

Hello, I am working on a game ( kinda of but, i want to learn all the ins and outs of how to do things before starting ) This is something I have been wondering this is the code

I understand what the code does however I don’t know the code to change from when the object collides with the floors to if a player presses a button

function OnCollisionEnter (myCollision : Collision){
 If(myCollision.gameObject.name == "Floor"){
 Application.LoadLevel("Level01");
}
}

5 Answers

5

First of all, I think your question is a bit unspecific.

If what you want to do is to load another level when the player presses a button in a GUI, you will have to use OnGUI(). Documentation for basic GUI scripting can be found here: http://unity3d.com/support/documentation/Components/GUI%20Scripting%20Guide.html

Then, your code would look something like this:

    function OnGUI () {
     	if (GUI.Button (Rect (10,10,150,100), "Load another level..")) {
     		Application.LoadLevel("Level01");
     	} 
  }

If this is not what you want, then please specify further. What is the setup? Do you want to use a button in a GUI or a gameObject as the button?

lets say you want to press a GUITexture:

function OnMouseDown () {
//Do some sexy stuff here
}

You would ad this to the GUITexture or a 3DText, or even scripted GUIButtons.

This is what you would also use if you want to make a gameObject to be the button. Just use functions OnMouseEnter, OnMouseDown and the like, then throw it on the gameObject and you're good to go..

Collisions are completely unrelated to Unity GUI. Use a GUI.Button. It returns a boolean = true when the button is pressed by a user.

Therefore, if you wanted to load “Level01” when a button is pressed, try this:

function OnGUI () {
if (GUI.Button(Rect(10,70,50,30),"Click me! I change the level!")) {
Application.LoadLevel("Level01");
}
}

Too easy. :slight_smile: Klep

Uhm, isn't this exactly what is already answered?

Yeah sorry, my page hadn't refreshed when I wrote the answer ... :\ I hate that ... @MidnightPride: PeterDK's answer is the one you want! He answered first! :)

Thank you for all the responses and, they were helpful and, i will be keeping them in mind however I apologize for not being specific enough. I didn’t mean if they pressed a GUI button but, rather a keep board button ( Such as F ) as a result the world would load a new scene.

In that case what you’re looking for is e.g. Input.GetKeyDown(KeyCode.F).

Documentation can be found here:
http://unity3d.com/support/documentation/ScriptReference/Input.GetKeyDown.html

This function HAS to be called inside Update(), so implemented in your code it look like this:

function Update () {
    if (Input.GetKeyDown (KeyCode.F))
        Application.LoadLevel(Level01);
}

And another time, please don’t post comments as an answer. Use the ‘comment’ option under each answer :slight_smile:

Hope you succeed with your game…