- Home /
How do i reference a non static singleton?
I haven't been able to find anything useful on this considering I don't know how to look for it, but I was told to make a singleton for my code since I needed a variable that could be used on another script since the variable is being changed. But when I use it on another script it does not produce the same number since it is static. So basically the first code is:
public int itemNumber;
static public classname instance;
void Start()
{
itemNumber = Random.Range (0, 7)
}
And in the other script I try to use whatever number itemNumber generated by doing:
public int itemNumberTwo
SpinWheel.instance.itemNumber = temNumberTwo
But when I run the script it later does not result in the same numbers I'm guessing because it is static. I try to remove that part but then it says an object reference is needed to access the non-static field. Any ideas? Sorry if the way I tried to explain this doesn't make sense don't know a bit of C# mostly just java.
Answer by OreoSplitter · Apr 01, 2019 at 10:36 PM
I'm not too experienced but I myself have given up on using static. Can't use monobehavior, methods might need to be static, and possible serialization issues. What I would do is just put that script on a gameobject, make it public but not static, and use getcomponent().itemNumber = 5;
If you do want to use static try using a namespace.
using UnityEngine;
namespace myscripts
{
public class SpinWheel : MonoBehaviour
{
static public int itemNumber;
void Start()
{
itemNumber = Random.Range(0, 7);
}
}
}
using UnityEngine;
using myscripts;
public class Script_2 : MonoBehaviour
{
private void Update()
{
if (Input.GetKeyDown(KeyCode.M))
{
SpinWheel.itemNumber = 5;
print(SpinWheel.itemNumber);
}
}
}
Answer by jstopyraIGG · Apr 01, 2019 at 05:56 PM
if you only have one SpinWheel in your scene, I do suggest using a singleton. Here is how you can use a singleton!
public class SpinWheel : MonoBehaviour
{
public static SpinWheel instance = null;
Awake()
{
if(instance != null)
{
//SpinWheel already exists in the scene! this is a second SpinWheel!
}
instance = this;
}
}
Your answer
Follow this Question
Related Questions
How do i reference a non static singleton? 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
how do I create a static Instance in javascript 2 Answers
Static gameObject? 3 Answers