anszwa
1
Hi folks, I have following question. I know that I can assign a script with GetComponent() but if I have two scripts which I have already assigned, can I also save them in a third variable? Here is an example of what I want to do:
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
public bool hardMode = false;
private GameCameraNormal cameraNormal;
private GameCameraAdvanced cameraAdvanced;
// this is my problem, I dont know how to declarate this variable
private noIdea? currentScript;
private void Awake () {
GameObject mainCamera = GameObject.FindWithTag("MainCamera");
cameraNormal = mainCamera.GetComponent<GameCameraNormal>();
cameraAdvanced = mainCamera.GetComponent<GameCameraAdvanced>();
if (hardMode) {
//here I want to save the respective script in a variable
//so I can later access it without these request, for example:
currentScript = cameraAdvanced;
}
else {
//same here
currentScript = cameraNormal;
}
}
private void Update() {
// now here I want to access the respective script more than once,
// without having to ask for the right one with the boolean each time
currentScript.DoSomething();
}
}
Thanks for your help in advance!
Memige
3
Are you familiar with Class Inheritance? It sounds like what you want is the ability to store multiple different script types in one unified variable. To do this you can define an abstract base class that each of your potential scripts inherit from, you should then be able to create a variable of the base class type, that will be able to hold any object that inherited from it.
an easy example would be if all your scripts were monobehaviors you could store them all in a variable like so
C#
private MonoBehaviour thisScript = this;
void changeScript()
{
thisScript = GetComponent("SomeOtherScript") as MonoBehaviour;
}
A limitation of this is you can only call methods that are defined in the base class, so you would need to make sure that you have declared virtual functions for everything you will need in the base class
ScottW
2
Instead of setting the current script, just enable the script you want and disable the other.
Normal:
normalCamera.enabled = true;
AdvancedCamera.enabled = false;
Opposite for hardmode.