I don't understand why "Null pointer Exception" in Unity? [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
in my C# lives class I have a class attribute:
public int life = 0;
and in my C# loose class (so, another script), I want to access to my life attribute of my lives class, but i don't succeed, how to do it ?
When I do
var lv = new lives ();
int lv1 = lv.life;
It shows me that Unity does not allow. I MUST use GetComponent
so I do with get component
var lv = gameObject.GetComponent<lives> ();
int lv1 = lv.life;
And I have a null pointer exception, so it is not understandable ?

You don't use new to create a reference to MonoBehaviour derived classes.
The GetComponent call needs to be associated to the gameobject that class is actually on like this:
public GameObject objectWithLives; // populate this e.g. via inspector
...
Lives lives = objectWithLives.GetComponent<Lives>(); // NOTE: Always start classes with an uppercase!
Saying
Lives lives = gameObject.GetComponent<Lives>();
only works if that script is on the same object as this script.
You don't need to actually store the variable of that other script into a local variable (at least if they shall refer to the same value, otherwise you can do that). Just say something like
lives.life = 5;
If that class (script) actually is not meant to be on a gameobject then you don't derive from MonoBehaviour (that's not a must, only if you need stuff from MonoBehaviour and/or want to put the script on an object).
If you don't derive from MonoBehaviour then you use the standard way of referencing the class by saying new Lives().

Related

A NullReferenceException using Unity.5.6.5 with a script reference [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 years ago.
There are 3 Scripts at play in the problem I am experiencing.
Firstly I have an object which I whish to select which the following code to comunicate with the "GameManager"(the secound relavent object) that it is the selected object this works:
public void OnMouseDown ()
{
if(TheGameManager.SelectableOn || TheGameManager.SelectedObject == this){
//If clicked and not already selected then determain this as the selected object
OnOff = !OnOff;
if(FindObjectOfType<GameManager>().SelectedObject != this){OnOff = true;}
if(FindObjectOfType<GameManager>().SelectedObject == null){OnOff = true;}
//Determain this as the selected object
if(OnOff){FindObjectOfType<GameManager>().SelectedObject = this; TheGameManager.UpdateZUIInterface("close");}
else{FindObjectOfType<GameManager>().SelectedObject = null;TheGameManager.ResetAllUIToDefault();}
TheGameManager.UpdateAllUIElements();
}
This is how it looks in the inspector
Picture of the first object being selected
The problem occures however when I try to reference this instance safed within the GameManager.
[SerializeField] GameManager TheGameManager;
public void OnMouseDown (){
Selectable SelectedObject = TheGameManager.ProvideSelectedObject();
Debug.Log(SelectedObject.gameObject);
Debug.Log(TheGameManager.SelectedObject.GetComponent<Selectable>().gameObject);
}
Neither of these two ways to acces the instance works. I could imagine a direct reference send from the instance itself would work however I try to use the GameManager as a central storage of most of the frequently uses variables so i would like to avoid doing that. Do any of you have any solution or thoughts?
I would love to hear from you.
If the TheGameManager is setup as a Singleton, then it likely has a static instance property or field. In that case, you should be calling the static isntance field instead of a local instance of the TheGameManager
So, remove:
[SerializeField] GameManager TheGameManager;
And now call the game manager like this:
varSelectedObject = TheGameManager.instance.ProvideSelectedObject();
This is supposition, but I dare say it's the cause of your problems. If this isn't the case, we'll need to see the actual code for TheGameManager.

Accessing GetComponent() without instantiating

I am new to Unity Game Development and I find the following usage in code a bit confusing.
private Transform enemy;
// Start is called before the first frame update
void Start()
{
enemy = GetComponent<Transform>();
}
According to the documentation GetComponent() is a public function. So how can this be accessed without being instantiated?
I found a similar question was asked on Unity's community but I didn't find any of the answers answering the question exactly to the point. Please help me in understanding this.
The link to question on Unity forum is below.
Question
My Unity version is 2018.4.16f1
Thanks!
Your class most probably inherits from MonoBehaviour which inherits from Behaviour which inherits from Component.
Component implements GetComponent
Fazit: The instance which you are calling this method on is no other than this, the instance Start is called on.
Btw for Transform there is already a dedicated property Component.transform so you should not use GetComponent for getting a Transform reference.
you are calling the GetComponent() method of the GameObject you added your MonoBehavior to and assign it to the Transform enemy. It is even the first Answer from your linked Question.

Problem with Unity and C#. Script error. Does anybody know how to fix this? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
enter image description hereSo I have started to make a game (With very limited knowledge) using Unity.
Its a 2D game. I have created a script which is for health, food .. ETC..
As soon as I try to load this into unity It comes up with the following error?
'Can't add script component 'Game Manag' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.'
Any Ideas?
https://i.imgur.com/mhEodFW.jpg
Alright looks like you have quite a few errors in your code. You must post your code here, do not post a screenshot. Firstly I would say create a new script with name GameManager. Make sure there are no spaces between Game and Manager. Secondly, your Debug.Log is throwing errors as well.
I have corrected those errors and posted your error-free code below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
int Health;
int Day;
int Food;
int Money;
// Use this for initialization
void Start () {
Health = 100;
Food = 100;
Day = 0;
Money = 0;
Debug.Log(Health);
}
// Update is called once per frame
void Update () {
}
}

Unity C# error in variable decrementation [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I make a game in C# under Unity and I have a problem with the code for attack.
I've already tried to put this code in a void in the enemy script.
Enemy code :
public int Life = 5;
public int Speed = 100;
Player attack code :
// Use for player attack
public void Attack () {
if (Input.GetKeyDown("space")) {
EnemyD.Life = EnemyD.Life - 1;
}
}
// Use for Auto Attack
public void AutoAttack () {
EnemyD.Life = EnemyD.Life - 1;
}
Unity return this error :
error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement.
Thank you for your help, Jason.
If all enemies or group of enemies will have the same script, then you could call a particular script by grabbing whichever enemy was hit.
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Monster"))
{
collision.gameObject.GetComponent<EnemyD>().Life -= 1;
}
}
So if you have two enemies and you've attacked the first one, only on him will be applied this action.
Try to put scripts with proper Class name, I guess your enemy script is named EnemyD.
Let's come to point - your player is trying to access member without an instance, so it is a error.
If you try to access them without instance you have to put static before members , which means Of the class , Not of an instance.
Normally there is so many enemy, we don't use static, instead use the approach of Nikola G. from here [Posted as answer in this question].
Some links you might find helpful :
Static Variable
Class Variable

Unity, powerup collision issue [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm getting some issues with logic and the behavior that is happening in my game.
I want to implement a powerup and this powerup just stops that character for certain of time. So to do it I'm simply disabling his script so he does nothing. Now this is working but the problem is I can't find a way to enable the script back to him after 5 seconds. I want to stop the character for 2 seconds.
Your code is wrong. You should be using Invoke.
It is extremely simple.
Something like ...
void ApplyPenalty()
{
yourPauseSystem = true;
Debug.Log("starting penalty..");
Invoke("EndPenalty", 5f);
}
void EndPenalty()
{
yourPauseSystem = false;
Debug.Log(" ...ended penalty");
}
Don't forget the Debug.Log statements.
Note that ideally ApplyPenalty (and EndPenalty) should be
ACTUALLY ON THOSE GAME OBJECTS.
actually put that code ON THOSE game objects, NOT here in the "collision object code". You get it?
So in your case, to apply the penalty, it will be something like ..
void OnCollisionEnter(Collision c)
{
if ( (c.gameObject.tag == "Character") )
c.GetComponent<YourHerosCode?().ApplyPenalty()
}
you see?
You MUST use the physics layers system. You literally have to use it to make collisions in Unity. you MUST use the "physics grid"...
to indicate what can collide with what. In your comment you say they "won't collide" but you can absolutely make anything collide (or not collide) with anything.
Note that in practice EVERYTHING needs its own physics layer, in Unity.
Certainly your hero, enemy etc will all have their own layer.
Tip: certainly "enemy projectiles" and "player projectiles" need their own separate layer, both.
If NullReference is on this line gameObject.GetComponent<PlayerControls>().enabled = true; is probably because you try to reference to a disable component.
Try to assign a var in Start() to the component
var playerController = gameObject.GetComponent<PlayerControls>();
and then use this to refer to it and enable/disable it:
playerController.enable = true; //or false

Categories