- Home /
C# Change Script Help
Hello Everyone, I have a script that I'm trying to make so it changes the someGameObject into switchOut. Everything's working fine except when I click the change button someGameObject doesn't change into switchOut but makes someGameObject equal to switchOut. How do I get it so it changes someGameObject and not change what it equals?
using UnityEngine;
using System.Collections;
public class SomeScript : MonoBehaviour {
public string[] someStringArray;
public string someString;
public GameObject switchOut;
public GameObject someGameObject;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void OnGUI () {
if(GUILayout.Button("Change", GUILayout.Width(75), GUILayout.Height(25))){
someGameObject = switchOut;
}
}
}
Answer by Hotshot10101 · Jun 22, 2013 at 05:01 AM
If I understand what you are trying to do you will want to do something like this:
someGameObject = Instantiate (switchOut, position, rotation);
That will clone the switchOut object and create a new instance of it. I think that is what you asking, yes?
Yes I think that's what I want. I'm getting an error from the console saying I can't implicitly convert unityEngine.Object to unityEngine.GameObject .
someGameObject = Instantiate (switchOut, someGameObject.transform.position, someGameObject.transform.rotation);
Yea, just add as GameObject like this:
someGameObject = Instantiate (switchOut, position, rotation) as GameObject
;
or
someGameObject = (GameObject)Instantiate (switchOut, position, rotation);
I like the first method myself, but they are mainly the same.
Obviously you will have to have a valid position and rotation.
Can't I assign someGameObject the same position and rotation that it Already has?
Yes you can. If someGameObject is already pointing to an existing game object do you want it to be destroyed? If so you will want to save the position and rotation from it and then call Destroy (someGameObject) to destroy it and then make the someGameObject = Instantiate call with the saved position and rotation.
Your answer
Follow this Question
Related Questions
C# Adding Components From Other Gameobjects 3 Answers
Destroy + Score 1 Answer
C# Raycast 2D GameObject follow Mouse 1 Answer
C# SetActive GameObject Array 2 Answers