- Home /
Is it possible to change a variable, into a script not assigned to any game object?
Hey guys, One exemple, i have two scripts, script A is assigned to a empty into my scene, and script B is one script to help many things into the application, but it's not assigned to any game object in any scene, and it has a int variable, and a want modify the value of this variable from my A script, is it possible?
Yes, of course it is. If it's a static class, you can just use ClassName.$$anonymous$$yIntField = Value. If it's not a static class, you can just store an instance inside the Script A class and use that.
I've been trying the second way u said, but unity still saying that object reference not set to an instance.
@PTerto - That's probably because the class isn't static. In your Script A, you need to make sure you have an instance. In C#, you'd store a field like private ScriptBClassName _variableName
and then do something like void Awake() { _variableName = new ScriptBClassName(); }
Then when you need to use the code in that class, you would reference it with _variableName
.
But, the way u are saying, i'll be creating another element, ScriptBClassName, am I wrong?
Answer by Visual Programmer · Sep 25, 2013 at 05:04 PM
If you use a public static variable it can be accessed from anywhere. I believe it still holds true if it is not attached to an object. For example, I can access this float var from any script without it being attached to the same object.
public static var myFloat:float;
Yes, when it is static, it holds the value regardless of being attached to a game object.
Answer by Tanshaydar · Sep 25, 2013 at 04:59 PM
If script B is deciding many things for the game, then it should be something like a Game Controller, which usually is assigned to a empty Game Object in the scene. For example, you create an Empty Game Object and name it as Game Controller and then assign the script to it.
If you don't want to assign the script to any object, then you can make your variables static, so that it should be available like YourScript.staticVariableName
and you can use or assign values to it. Like if( YourScript.staticVariableName == anotherValue)
or YourScript.staticVariableName = anotherValue;
Answer by PTerto · Sep 25, 2013 at 05:45 PM
using UnityEngine;
using System.Collections;
public class GuiMainMenu : MonoBehaviour {
private string keySound = "AUDIOGAME";
public AudioSource click;
public GeneralGameSound x;
void Start ()
{
x = GetComponent("GeneralGameSound") as GeneralGameSound;
}
x.teste +=1;
void Update(){
}
This was the A script, and this
using UnityEngine;
using System.Collections;
public class GeneralGameSound : MonoBehaviour {
public int test = 10;
private static string x = "GONE";
public static void setTeste(int at)
{
PlayerPrefs.SetInt(x,at);
PlayerPrefs.Save();
}
public static int getTeste()
{
return PlayerPrefs.GetInt(x,0);
}
is the B Script, what am i doing wrong?
It looks like you need to change test to public static int test