So I was looking into implementing the new Unity input system into my game by reworking my code in my PlayerController script and got stuck pretty early on.
Here is the code that causes issues:
private PlayerInput playerInputController;
private void Awake()
{
playerInputController = new PlayerInput();
}
A green scribbly line appears under the 'Awake()' bit.
The code itself actually works, but it causes a lof of other issues, which makes a bunch of error messages appear saying:
NullReferenceException: Object reference not set to an instance of an object
The error messages all lead to places where I've used lines of code like this one in other scripts, to get variables and methods from my PlayerController script:
if (PlayerController.instance.isGroundedPhys)
Lastly, here's my singleton script, since it's likely relevant, as it's connected to my PlayerController script and allows it to be accessible from other scripts:
using UnityEngine;
public class Singleton<Instance> : MonoBehaviour where Instance : Singleton<Instance>
{
public static Instance instance;
public virtual void Awake()
{
if (!instance)
{
instance = this as Instance;
}
else
{
Destroy(gameObject);
}
}
}
This bit is at the top of my PlayerController script to make it accessible from other scripts:
public class PlayerController : Singleton<PlayerController>
{
I've been looking around and can't find anybody talking about similar issues. I think it's related to my singleton script, but I can't figure it out. :[
[Edit]:
I just found out it also gives this warning in the Unity console:
warning CS0114: 'PlayerController.Awake()' hides inherited member 'Singleton<PlayerController>.Awake()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
PlayerInput is a MonoBehaviour!
No seriously, this is "Not Allowed" and you should actually give you an according warning in the console.
A MonoBehaviour "can"/should only exist attached to an according GameObject and always be created by the underlying c++ framework. It's a c# thing that Unity can't fully prevent you from using new to create one.
The only valid way of creating an instance of a MonoBehaviour are
Instantiate a prefab that has the component attached
use AddComponent on an existing GameObject
use the constructor of GameObject and pass in the according component type(s)
Or you probably rather want to use e.g. GetComponent or FindObjectOfType in order to get a reference to an already existing instance of PlayerInput.
And then the other warning means you implemented
public void Awake()
{
// ...
}
or similar in your PlayerController class. The warning already tells you exactly what to rather do:
// Use "override" in order to not hide the already existing implementation
// of "Awake" in the base class
public override void Awake()
{
// Make sure the base class behavior is executed
// this will initialize the Singleton thing
base.Awake();
// ... your additional behavior here
}
Related
I have three of classes that I am using in my game and I got curious about Singleton pattern.
I have used singleton to access variables or functions easier and I didn't know how to access it without using a singleton pattern only except making "public GameObject" variable and assign object that has a script that I need in inspector.
under here is my sample code
public class ExampleClass : MonoBehaviour
{
public static ExampleClass instance;
private void Awake()
{
instance = this;
}
}
public GameObject assignScriptObject;
as you see, in the ExampleClass I used singleton pattern that I made
and at the las line is how I will assign script in inspector.
Is it fine to use Singleton pattern
(I call functions a lot by using that instance)
{i.e. ExampleClass.instance.LoadSomeFunctions() } there are dozens of lines with other functions
OR
Is it better to assign script in inspector
as an aspect of optimization.
THANKS!
I've seen this question several times on the site, however most of the solutions seem to indicate that I should just make it an instance variable rather than a static one. However, the whole point of the Singleton pattern is this static object that's consistently referred to. Here are the links I have looked at:
Member cannot be accessed with an instance reference; qualify it with a type name
Member '<method>' cannot be accessed with an instance reference
This last link led me to the following:
What does the 'static' keyword do in a class?
And I feel I do understand this. The point of the Singleton is that all classes share this one instance so it feels perfect? I don't see the issue? It should be static according to Singleton conventions and frankly logic.
I'm in unity and am trying to make an inventory system for a game some fellow students and I are trying to make. I have the InventoryUI set up, however I would like to build a static inventory that is ever-present in the game. The InventoryUI will draw the necessary data from this Singleton class.
In other words, the PlayerInventory will act as the backend for the InventoryUI. The PlayerInventory will be a Singleton and the InventoryUI will draw the necessary data from PlayerInventory
Here is the relevant code for my Singleton class:
public class PlayerInventory : MonoBehaviour
{
private static PlayerInventory instance;
private PlayerInventory() { }
public static PlayerInventory getInstance()
{
if (instance == null)
return instance = new PlayerInventory();
return instance;
}
}
Here is the relevant code for my InventoryUI class:
public class PlayerInventoryUI : MonoBehaviour
{
//Inventory Instance
static PlayerInventory inventory;
void Start()
{
inventory = inventory.getInstance();
//cannot be accessed with an instance reference Error occurs here.
}
}
If possible, could someone explain to me why this error occurs as well as a possible solution.
That static method is in the class, not in an instance. So change your code in InventoryUI to this:
public class PlayerInventoryUI : MonoBehaviour
{
//Inventory Instance
static PlayerInventory inventory;
void Start()
{
inventory = PlayerInventory.getInstance();
//works because static methods are called from the class
}
}
I use Singletons with Unity a lot, have shared my pattern in a Quora answer: https://qr.ae/TSqaWt
Oh and if your Inventory is not in some GameObject Script component, it does not need to inherit from MonoBehaviour. Is better to use just a plain C# class if you don't need to use MonoBehaviour things like having Unity call Update on it.
If you wan't to have it as a script component, which can be nice to have it show in the inspector etc, then you should not 'new' it yourself but let Unity create it and assign the instance to the static reference when that happens. Is good to do that in Awake() so the singleton is already there when other scripts do Start()
Try the following instead:
inventory = PlayerInventory.getInstance();
You are attempting to call a static method on an (uninitialized) instance variable which is not allowed. Static methods must be qualified with the type (class) name, as the error suggests.
You have defined a static method inside a non static class, and although it's perfectly legal, the two should be thought of as seperate entities. Static methods only have access to static fields of the class, they cannot access any instance variables. The memory of static data members is allocated individually without any relation with the object.
Look at String.Parse() as an example, you wouldn't write mystring.Parse(), but instead you use the static method Parse of the String class which is always available and does not require a new string instance to use.
Hope this helps, if any further questions I will try to explain better.
I am making a game in Unity C# where the character will have different characterstics and movement functions in each scene. So I am trying to have different scripts for a player in different scenes, while all of them inheriting from the same base class. The definition will be something like below
public class PlayerScript1 : PlayerBase { /* for scene 1*/
public void Move(){
/* my movement code*/
}
}
Similarly, I have a separate class for Scene2 as
public class PlayerScript2 : PlayerBase { /* for scene 2*/
public void Move(){
/* my movement code*/
}
}
Now the problem is, my other scripts, like HealthScript,ScoreScript etc they do not change with scene. But they do access PlayerScript1 script. And thats why, I have the PlayerScript1 declaration in them. Like below:
public class HealthScript : MonoBehaviour {
PlayerScript1 playerScript;
void Start(){
/*accessing the script attached to game object*/
}
}
So how can I have my Health Script access different instances of my PlayerScript based on the scene? I know I could use delegates to call different methods in runtime, but how can I do the same with classes?
So how can I have my Health Script access different instances of my PlayerScript based on the scene?
Well first, you'll want to declare that object as of Type PlayerBase as you will be unable to assign an instance of PlayerScript2 to a variable of type PlayerScript1: those classes might inherit from the same parent, but they are not the same and you cannot convert from one to the other.
After that you will need to search for the player object in the scene, something like...
void Start(){
playerScript = GameObject.Find("Player").GetComponent<PlayerBase>();
}
Assuming, of course, that PlayerBase extends MonoBehaviour. If it doesn't you can't get a reference this way (as it won't exist in the scene at all). Additionally if you want this health object to persist from scene to scene, you need to call DontDestroyOnLoad() for it (as well as remembering that if you don't start testing from Scene 1 where this object is, it won't exist at all, or if you have a copy in every scene, you'll have duplication problems).
Someone answered to my question on the Unity forum which cleared all my doubts:
The key was using the below line in my HealthScript :
PlayerBase player = (PlayerBase)FindObjectOfType(typeof(PlayerBase));
http://answers.unity3d.com/answers/1348311/view.html
using UnityEngine;
using System.Collections;
public class VariablesAndFunctions : MonoBehaviour
{
int myInt = 5;
}
The full code is here Unity Official Tutorials
What is the purpose of MonoBehaviour
MonoBehaviour is the base class from which every Unity script derives. It offers some life cycle functions that are easier for you to develop your app and game.
A picture is worthy of thousands of words.
Source of the image: https://docs.unity3d.com/uploads/Main/monobehaviour_flowchart.svg
While the following statement is correct,
"MonoBehaviour is the base class from which every Unity script derives" -
I honestly feel it can be misleading to beginners. The phrase - "every Unity script" - being the culprit.
It gives a beginner the notion that all scripts created in unity must extend Monobehaviour. Which is not the case. You can create scripts that house classes that extend the c# base object class. In doing so, your script is then categorised as not a Unity script but nothing stops it from interacting with other Unity scripts and vice versa.
MonoBehaviour is another class that VariablesAndFunctions is inheriting from. This allows the inheritor to use the methods and variables of the other class providing they have the correct access level modifier set.
In the below example Class1 inherits from Base and so can use the protected method Method1
public class Base
{
protected void Method1 { /*...*/ }
}
public class Class1 : Base
{
public void Method2 { Method1(); }
}
Note in this particular example it would be better for Method1 to be marked as abstract or virtual so then Class1 can override it like so:
protected override Method1()
{
//...
base.Method1(); //Call the implementation of Method1 in Base here
//...
}
In particular though MonoBehaviour is described as being:
MonoBehaviour is the base class from which every Unity script derives.
Therefore when doing scripting in unity, you use this base class to better control how things are accessed so you do not need to do it yourself.
Monobehavior is what most of your scripts inherit from,
if you go to the documentation Click here!
you will see a bunch of variables and methods you get from this Inheritance.
such as:
Public Methods
Messages
Properties
Public Methods
Static methods
The most commonly used method (its under message in the documentation but honestly its better to see it as a function) is Update , its the main game loop, the speed at which the update function is called is based on your fps. But the important thing to take away is that if you didn't inherit from monobehavior, you wouldn't have access to this game loop.
Another important function that you get from Monobehavior is Start, which is called once on a script, and it's called after awake, so if you want to set some variables up you can do it here.
The important thing to take is that if you made a simple C# class that inherits from nothing, you wouldn't have access to these methods discussed. Monobehavior gives you access to many functions that help you build your game.
There are other behaviors your scripts can inherit from like ScriptableObject and StateMachineBehaviour, which give you access to other methods, but Monobehavior is the most common behavior your scripts will inherit from.
It's also good to note that whenever you use Monobehavior, it comes with a transform, some other scripts (Scriptable objects) don't come with a transform. The transform is simply a position in your game/scene where the gameobject lies its an x,y,z coordinate with rotation and scale.
I'm currently working on an inventory system in Unity3D, and came upon a weird problem. I have created non-MonoBehaviour classes for my inventory system (in case that matters), so that I have an Inventory class which holds a list of Slot objects, which in turn holds a list of Item objects.
Then I added a component script to my "HudInventoryPanel", called "HudInventoryController", which looks like this:
using UnityEngine;
using System.Collections;
public class HudSlotController : MonoBehaviour {
private InventoryController ic;
// Use this for initialization
void Start () {
ic = GetComponent<InventoryController>();
}
// Update is called once per frame
void Update () {
}
}
However, inside the Start() method, the InventoryController (part of my Player) hasn't been created yet, and it seems to me like the gameobjects are created in alphabetical order...?
How should I deal with this problem?
You can specify script execution order in the project settings (Edit -> Project settings -> Script execution order), so use that to make sure your scripts are executed in the correct order. In addition to that, you can use the Awake() method as all Awakes are executed before any Start() method. Hope a combination of these helps you!
I solved this by creating an intermediate variable in my InventoryController script, plus creating a "manual" getter; https://gist.github.com/toreau/f7110f0eb266c3c12f1b
Not sure why I have to do it this way, though.