Hi to all, i’m really newbie with Unity, and i’ve a question:
Is it possible to modify a variable from a script other than the one in which it is declared?
Welcome to the forums!
It’s absolutely possible to modify the value of a variable from another script. This can be done in a number of ways, some of which are more “correct” than others.
One way is to use public variables and just access that property from a reference to that first component. This seems to be the way most Unity documentation shows doing it:
public class MyClass : MonoBehavior {
public string name;
void Awake() {
name = "Bill";
}
}
public class MyOtherClass : MonoBehavior {
public MyClass myClass;
void SetNewName() {
myClass.name = "Ted";
}
}
The problem with this style is it makes the classes a bit too tangled up. It’s not obvious from looking at MyClass that the value of name is being set in another class. It also means that if you change something in MyClass, you have to update it in MyOtherClass as well. This is called “coupling” and is something you generally want to avoid once you start getting more advanced.
One option is to keep your variables private so that they can only be changed from within that class. You can use methods to provide access to those variables, so if you want to change how that value gets set, you only have to do it in one place.
public class MyClass : MonoBehavior {
private string name;
public void SetName(string name) {
this.name = name;
}
}
public class MyOtherClass : MonoBehavior {
public MyClass myClass;
void SetNewName() {
myClass.SetName("Ted");
}
}
Another option is to use properties instead, which give you easy ways to get and set the values of private variables. This comes in handy if you want to do extra checks or changes on a value before assignment or retrieval (which can be done with methods, too), and it keeps the code looking nice and clean where you use it.
public class MyClass : MonoBehavior {
private string name;
public string Name {
get {
if (String.IsNullOrEmpty(name)) {
return "No Name";
}
return name;
}
set {
if (String.IsNullOrEmpty(value)) {
name = "No Name";
} else {
name = value.Trim(new char[] {' '});
}
}
}
}
public class MyOtherClass : MonoBehavior {
public MyClass myClass;
void SetNewName() {
string previousName = myClass.Name;
myClass.Name = "Bill";
}
}
Okay, so how do you actually access one component from another in Unity? Generally you create a variable that has a type of that component’s class, like in my examples above. You then assign the reference to that component by dragging the item to it in the Inspector, or you can get it in code if you have a reference to a GameObject and then use the GetComponent<> method. Note that you should be using the typed version, not the one where you pass a string into the parameters. I’ll explain why when you’re older. ![]()
Does that help at all? I can provide further clarification on anything if you like.
Wow great answer, but this method work laso for boolen variables?
Let me explain, i’ve tryed declaring the boolen pubblic, but the other scripts cannot modify them.
I try to use your methid, thank you very much.
Just another consideration, with your first method i can declare all variable tha i need in only one class, and enclosing them in all the scripts thet modify them.
You can declare them all in a public class yes. It is highly recommended to know the fundamentals of C# before really diving into Unity. Sure you can mash together a game without coding, but it isn’t gonna be pretty. There are plenty of free and paid tutorials out there on the subject.
@Ext3nd-Studio It absolutely works with booleans and any other type. Can you share your code that isn’t working?
I’m following the learning pathway, but something i love to make some experiment.
@Schneider21 i’ve tryed your first method, but when i try to read the variale, Unity give me this error:
NullReferenceException: Object reference not set to an instance of an object
my code is this when i create the variable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Variable : MonoBehaviour
{
public bool Mission;
void Awake()
{
Mission = false;
}
}
and this when i try to read it and return the error
void Update()
{
if (variable.Mission)
{
// my code if mission is false
}
}
Could you share the entirety of both scripts? I’m assuming variable is of type “Variable” (these are horrible names, btw… consider naming them something more descriptive so the code is self-documenting), but best to be sure.
Also, where are you assigning the value of “variable”? Did you drag a reference to it in the Inspector or using GetComponent as I mentioned?
Ok, let me do it again
I’ve enclosed this script in a Game Manage Object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Variable : MonoBehaviour
{
public bool Mission;
void Awake()
{
Mission = false;
}
}
And this in another GameObject
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CapoScript : MonoBehaviour
{
public Variable variable;
void Start()
{
}
void Update()
{
if (variable.Mission)
{
Debug.Log("missione non attiva");
}
}
Update: sorry it’s working, i’ve forgotten a thing. Thank you to all.
The learning pathway is a good place to start. I have not done their coding / scripting pathway myself yet. But I would still advise watching a basic C# tutorial and learning the basics of that. With most unity courses it will show you how to do something and in the future you will be like okay, I remember this is how I do it. But you don’t know why it was done.
Honestly I have a smattering of various object oriented programming languages, the problem with Unity is that I have to learn how to interpret the various steps in the Inspector window