I'm working on creating a master script in Unity to control the other scripts. I'm stuck at one part which is the master script can call function from the others.
For example below is script B
public class B
{
void Test()
{
Dosomething;
}
}
Script A will be the master one that control script B. Is there any way that you can call Test() in script B like A.Test()?
I tried interface but then I still have to create another Test() function inside script A. This will be troublesome if I include more scripts with more functions.
Any advice would be appreciated.
This is from the Unity tutorials. Should be a good start...
public class UsingOtherComponents : MonoBehaviour
{
public GameObject otherGameObject;
private AnotherScript anotherScript;
private YetAnotherScript yetAnotherScript;
private BoxCollider boxCol;
void Awake ()
{
anotherScript = GetComponent<AnotherScript>();
yetAnotherScript = otherGameObject.GetComponent<YetAnotherScript>();
boxCol = otherGameObject.GetComponent<BoxCollider>();
}
void Start ()
{
boxCol.size = new Vector3(3,3,3);
Debug.Log("The player's score is " + anotherScript.playerScore);
Debug.Log("The player has died " + yetAnotherScript.numberOfPlayerDeaths + " times");
}
Okay, so the first things you should be aware about is that you really cant use static classes and functions in unity. That has something to do with every component on a gameobject essentially being a script the is instanced. So simply typing "using ScriptB" on the top and the calling the function like "ScriptB.Test();" really wont do anything.
What you need to do is to pass in a Script B reference as a variable in to Script A and then assign either drag it in editor or assign it via Script A. But in any case both scripts have to be in the same scene and assign to any game objects that are in that scene (they dont have to be on the same one)
So the final solution would look like this:
public class A
{
public B refToB;
void Start()
{
//we call the function here
refToB.Test();
}
}
public class B
{
public void Test(){
//we can do something here :)
}
}
Only thing for this to work is thet you need to assign the variable refToB through the inspector panel in the editor. A simple drag and drop action.
Hope it helps :)
Related
So im trying to change a variable in another script by touching a cube.
Current setup
1x Player
1x Enemy
Each with their own script Enemy_Stats & Character_Stats
As you can see in this little snippet it's quite a workaround to access the variable from another script.
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Enemy")
{
collision.gameObject.GetComponent<Enemy_Stats>().Health =
collision.gameObject.GetComponent<Enemy_Stats>().Health
- gameObject.GetComponent<Character_Stats>().AttackDamage;
if (collision.gameObject.GetComponent<Enemy_Stats>().Health <= 0)
{
Destroy(collision.gameObject);
}
}
}
Iam new to Unity, but isn't there a way to just refer it with something like:
collision.Health?
How to access variables/functions from another Class. The variable or function you want to access or called must be public not private.
public class ScriptA : MonoBehaviour{
public int playerScore = 0;
void Start()
{
}
public void doSomething()
{
}
}
Access variable playerScore in ScriptA from ScriptB. First, find the GameObject that the script or component is attached to with the GameObject.Find function then use the GetComponent function to retrieve that script or component that is attached to it.
public class ScriptB : MonoBehaviour{
ScriptA scriptInstance = null;
void Start()
{
GameObject tempObj = GameObject.Find("NameOfGameObjectScriptAIsAttachedTo");
scriptInstance = tempObj.GetComponent<ScriptA>();
//Access playerScore variable from ScriptA
scriptInstance.playerScore = 5;
//Call doSomething() function from ScriptA
scriptInstance.doSomething();
}
}
No since Health is not part of the collision object, but Enemy_Stats. You can cache a Component (that's what Enemy_Stats is) if you use it multiple times to save you some typing (and some performance, but that is rather marginal for this example). Also you can cache "known" components like in this case Player_Stats. You can do this e.g. in Start or with a public variable and the inspector.
What you should probably do though is to make the enemy be responsible for his life and not the player, so move the Destroy-part to Enemy_Stats (into the Health property to be exact).
The first thing to make this shorter (and eventually faster) would be to store this: gameObject.GetComponent<Character_Stats>() on Start() in a private variable (you should avoid calling GetComponent on a frequent basis if you can avoid it).
For the Health variable, a way of avoiding GetComponent calls could be caching: you create a Dictionary<GameObject, Enemy_Stats> and read from that as soon as this gameobject collided once
At the very beginning i mean in Awake() method you can find a game-object with tag
and get it's Heath after that in Collision() method you should just decrease the health but, here the condition is there is only one enemy and only one player.
I want something like this.
ComponentTest.cs - This script is attached to a empty game object in the scene.
public class ComponentTest : MonoBehaviour {
public GameObject boxPrefab;
void Start () {
GameObject temp = Instantiate(boxPrefab, new Vector3(0,0,0), Quaternion.identity) as GameObject;
temp.GetComponent<PrefabBox> ().go = gameObject.GetComponent<ComponentTest>().Yes();
}
public void Yes(){
print("yes");
}
}
and PrefabBox.cs - This script is attached to the prefab.
public class PrefabBox : MonoBehaviour {
public GameObject go;
void Start () {
go ();
}
}
I get this as error:
The member `PrefabBox.go' cannot be used as method or delegate
First of all, the go object is declared as a GameObject but then you assign a function to it and then call it like a function.
It looks like you want Closures in which you can store functions to variables and call them in the way you do.
This post covers it: http://answers.unity3d.com/questions/494640/capturing-a-variable-in-a-closure-behaves-differen.html
Seems the data type needs to be Action but best to read up on it to grasp it properly.
Good luck.
I am trying to access a function, with a bool parameter, from one script to another and just can't get it to work. I have been looking around to try to understand what i am doing wrong.
Here is the script i am calling:
public class MainScript : MonoBehaviour {
public void ManageBoxCollider2D (bool shouldColliderBeEnabled) {
print (">>>>>>>>>>>>>>>>ManageBoxCollider2D: " + shouldColliderBeEnabled);
}
}
I am trying to call it from this script:
public class Sidebar1_Script : MainScript {
public MainScript mainScript;
void Start () {
mainScript.ManageBoxCollider2D (true);
}
}
There is a lot of other stuff in the scripts as well but this is what matters for this question
In the "Sidebar1_Script" I am trying to access "ManageBoxCollider2D" in "MainScript" but it does not work.
I do get the following message:
Object reference not set to an instance of an object
...which i do understand but can't figure out what i am doing wrong.
I would appreciate some help how to do this.
Thanks
It's because unity doesn't know what script that is. If you see in the inspector you're gonna find that public variable MainScript is still empty, also you can't assign scripts in the inspector (I don't know why though, when you drag it there it won't fit in).
Instead change your Sidebar1_Script like this:
public GameObject obj;
void Start () {
MainScript main = obj.gameObject.GetComponent<MainScript>();
main.ManageBoxCollider2D(true);
}
And then assign the game object of obj in the inspector (drag the game object to the public variable).
For example I have a variable (public static float currentLife) in script "HealthBarGUI1" and I want to use this variable in another script.
How do I pass variable from one script to another C# Unity 2D?
You could do something like this, because currentLife is more related to the player than to the gui:
class Player {
private int currentLife = 100;
public int CurrentLife {
get { return currentLife; }
set { currentLife = value; }
}
}
And your HealthBar could access the currentLife in two ways.
1) Use a public variable from type GameObject where you just drag'n'drop your Player from the Hierarchy into the new field on your script component in the inspector.
class HealthBarGUI1 {
public GameObject player;
private Player playerScript;
void Start() {
playerScript = (Player)player.GetComponent(typeof(Player));
Debug.Log(playerscript.CurrentLife);
}
}
2) The automatic way is achieved through the use of find. It's a little slower but if not used too often, it's okay.
class HealthBarGUI1 {
private Player player;
void Start() {
player = (Player)GameObject.Find("NameOfYourPlayerObject").GetComponent(typeof(Player));
Debug.Log(player.CurrentLife);
}
}
I wouldn't make the currentLife variable of your player or any other creature static. That would mean, that all instances of such an object share the same currentLife. But I guess they all have their own life value, right?
In object orientation most variables should be private, for security and simplicity reasons. They can then be made accessible trough the use of getter and setter methods.
What I meant by the top sentence, is that you also would like to group things in oop in a very natural way. The player has a life value? Write into the player class! Afterwards you can make the value accessible for other objects.
Sources:
https://www.youtube.com/watch?v=46ZjAwBF2T8
http://docs.unity3d.com/Documentation/ScriptReference/GameObject.Find.html
http://docs.unity3d.com/Documentation/ScriptReference/GameObject.GetComponent.html
You can just access it with:
HealthBarGUI1.currentLife
I'm assuming that HealthBarGUI1 is the name of your MonoBehaviour script.
If your variable is not static and the 2 scripts are located on the same GameObject you can do something like this:
gameObject.GetComponent<HealthBarGUI1>().varname;
//Drag your object that includes the HealthBarGUI1 script to yourSceondObject place in the inspector.
public GameObject yourSecondObject;
class yourScript{
//Declare your var and set it to your var from the second script.
float Name = yourSecondObject.GetComponent<HealthBarGUI1>().currentLife;
}
TRY THIS!
//Drag your object that includes the HealthBarGUI1 script to yourSceondObject place in the inspector.
public GameObject yourSecondObject;
class yourScript{
//Declare your var and set it to your var from the second script.
float Name = yourSecondObject.GetComponent<HealthBarGUI1>().currentLife;
I have to access variable ammoMagazine from this class
public class Pistol : MonoBehaviour {
public int ammoMagazine = 7;
}
then i tried this code :
public class AmmoCounter : MonoBehaviour {
public int ammo;
private Pistol _pistol;
void Start () {
_pistol = GetComponentInChildren<Pistol>();
}
void Update () {
ammo = _pistol.ammoMagazine;
guiText.text = "Pistol: " + ammo + "/7";
}
}
Why there's NullReferenceException: Object reference not set to an instance of an object ?
Thanks, im new in C#
There is probably no value assigned to the _pistol field, so either you didn't call Start before you called Update, or GetComponentInChildren<Pistol>() returned null.
public class AmmoCounter : MonoBehaviour {
public int ammo;
private Pistol _pistol = GetComponentInChildren<Pistol>();
void Update () {
ammo = _pistol.ammoMagazine;
guiText.text = "Pistol: " + ammo + "/7";
}
}
Initialize the _pistol-variable before calling the update-function (Check if the GetComponentInChildren()-function returns null)
Note that it's NullReferenceException.
I think for some reason Update() is being called before Start().
I know this has already been answered..but I think there will be some roadblocks ahead for you if you code everything with private variables like the accepted answer. Usually to get a reference in Unity you need to have an object in the scene with the desired attached script. So first you would re-write the script:
public class AmmoCounter : MonoBehaviour {
public int ammo;
public GameObject _pistol;
void Start( ){
ammo = _pistol.GetComponent< Pistol >( );
}
void Update( ) {
guiText.text = "Pistol: " + ammo + "/7";
}
}
In the scene you want an object with the Pistol script attached, then in the editor ( inspector ) you should drag that object into the _Pistol slot. There are several reasons for doing this but two important ones are 1) You're shortening the code and referencing the script once ( the current answer is duplicating the reference ) and 2) Using GetComponentInChildren is inefficient; Unity searches through every game object underneath a parent to get your component. Thus, a direct object reference is better. Also using this type of object reference will save you several headaches in the future, most notably easy reference and making it easier to follow your own code in the future ( you can see the reference in the editor rather than looking through code -- trust me magical references can be a nightmare ).
If you don't want to reference through objects read up on the static type in C#, this allows you to reference items without using GameObjects. However, static types are finicky creatures, so be careful and know what you're doing before using them
edit: grammar