Reputation: 321
I'm having a difficult time trying to add and remove a js script as a component to a gameObject in C#, as I'm novice to Unity and coding.
I have a js that needs to be added in MainCamera in runtime, by click of a GUI.Button. This script has to be destroyed later with the same GUI.Button clicked.
I have managed to add the js script on the MainCamera in runtime with the following code snippet:
public Bearing addBearing; // "Bearing" is the js script and "addBearing the variable to reference this
//some other codding
.
.
// Add and remove Bearing with this button
public bool addBearing;
void OnGUI(){
if(GUI.Button(new Rect(10,10, 100, 100), "Bearing"))
addBearing= !addBearing;
if(addBearing){
addBearing = GameObject.FindGameObjectWithTag("MainCamera").gameObject.AddComponent<Bearing>();
}else{
GameObject.FindGameObjectWithTag("MainCamera").gameObject.GetComponent<Bearing>();
Destroy(GetComponent<Bearing>());
Problem is, that when I click back the "Bearing" GUI.Button, js script "Bearing" is not get destroyed as it should.
There is something missing in this code logic, but I'm not that experienced in coding C# to find a solution. So, can someone be kind enough to get me a helping hand with this code? It would be very much appreciated. Thank you all for your answers.
Upvotes: 0
Views: 4117
Reputation: 124
When you call GetComponent<Bearing>()
, you are getting the Bearing
component on the object within the current scope. If you do not specify a scope, then it will look for a component on the GameObject that the script is attached to. So instead of:
Destroy(GetComponent<Bearing>());
Instead, you want:
Destroy(GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Bearing>());
GameObject.FindGameObjectWithTag
establishes the scope, then GetComponent<Bearing>
gets a reference to the Bearing
component on whatever scope was established before it. So combining those two will get you a Bearing
component from the Main Camera, which is passed into the Destroy function which destroys it.
Upvotes: 2
Reputation: 364
instead of adding and destroying, why don't you use
GetComponent(Bearing).enabled = false; to disable and
GetComponent(Bearing).enabled = true; to enable
Upvotes: 5