Changing a GameObject By Clicking a Button

Hello everybody I only have very basic programming knowledge so I thought I would ask on here for help, what script would you write so that when you press a button on screen a GameObject will change. I am planning to use this so that once I press a button on the screen the GameObject (a hammer) will switch/ be replaced by another GameObject (a sword or something like that)

Many thanks in advance! :slight_smile:

Something like this:

public Mesh changeMesh;
public GameObject targetObject;

void OnGUI() {
  if ( GUI.Button( new Rect( 0,0,100,20 ), "Change" ) ) {
    targetObject.renderer.mesh = changeMesh;
  }
}

Thank you for such a fast reply however I’m having a few problems, I get two errors when I try to use the script. “Unexpected Token: Mesh.” and “Unexpected Token: GameObject.” Any idea what I could be doing wrong? :slight_smile:

I was trying to write C#; I may have failed utterly, or perhaps you are using a .js file?

Oh, I bet C# has to have explicitly declared classes. I usually use Unityscript, so I know -this- will work (as a JS):

var changeMesh : Mesh;
var targetObject : GameObject;

function OnGUI() {

  if ( GUI.Button( Rect( 0,0,100,20 ), "Change" ) ) {

    targetObject.renderer.mesh = changeMesh;

  }

}

You might be able to get my first shot working if you encapsulate it in a class:

class ClassName : MonoBehaviour {
  // my stuff
}

Thank you again for your help :slight_smile: but I’m getting a new error, “MissingFieldException: Field ‘UnityEngine.MeshRenderer.mesh’ not found.
Boo.Lang.Runtime.DynamicDispatching.PropertyDispatcherFactory.FindExtension (IEnumerable`1 candidates)” I’m using your JavaScript script :slight_smile:

Am I fired yet?

“mesh” is a member of MeshFilter, not Renderer. >_<

target.GetComponent.<MeshFilter>().mesh = changeMesh;

Haha no your help is much appreciated :smile:, I had another error with the last bit of code but added “Object” after “target” and it now seems to be working perfectly :slight_smile: Big thanks for all your help :slight_smile:

if i have 100 btn how to make 100 onclick to one function

Please don’t reply to 9-year-old threads. It is against forum rules. Instead, start your own thread. It’s free!

When you post, please keep this in mind: how to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

How to understand errors in general:

If you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: Using code tags properly