user736893
user736893

Reputation:

Rotate dynamically created object only if it exists?

In the code below, I get an error (as expected) on line 7:

The name "cube" does not exist in the current context.

1. if (action == "place") {
2.     GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
3.     cube.transform.position = new Vector3(0, 0.5F, 0);
4. } else if (action == "rotate") {
5.     var x = Convert.ToInt32(message.Args["rotatex"]);
6.     var y = Convert.ToInt32(message.Args["rotatey"]);
7.     cube.transform.Rotate(x,y,0);
8. }

This is just for a proof of concept. I won't need to handle multiple cubes like this. So how should I instantiate it in the proper context (above this if statement) without "placing" it in the scene?

Upvotes: 0

Views: 60

Answers (2)

cmprogram
cmprogram

Reputation: 1884

You aren't declaring the cube in your 'else if' statement only your 'if' statement. So in your 'else if' it is referencing something that doesn't exist under that condition.

You can simply use a switch instead.

switch (action){
case 'place' :
//Declare Cube (Including Instantiate)
//Do what you want with Cube
break; 
case 'rotate':
//Declare Cube (Including Instantiate) 
//Do whatever else 
break; 
}

Upvotes: 1

Matt L.
Matt L.

Reputation: 768

You should declare the object first, and only rotate it if the value is not null. Something like this

GameObject cube = null;

if (action == "place") {
    cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
    cube.transform.position = new Vector3(0, 0.5F, 0);
} else if (action == "rotate") {
    var x = Convert.ToInt32(message.Args["rotatex"]);
    var y = Convert.ToInt32(message.Args["rotatey"]);
    if(cube != null)
        cube.transform.Rotate(x,y,0);
}

Upvotes: 2

Related Questions