How do i use a variable from another script [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 years ago.
Hi im having a problem with this i tried for 2 Days now but i don't know how to fix it. Im a beginner in C# and hope you can help me.
Im trying to use a variable from another script but the console keeps sending me an error:
NullReferenceException: Object reference not set to an instance of an object
PlayerCombat.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Scrips/PlayerCombat.cs:52)
public int attackDmg = 2; //Diffrent Script
public void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag == "Enemy")
{
PlayerTakeDamage(currentPlayerHp, GetComponent<Enemy>().attackDmg);
}
}
static void PlayerTakeDamage(int currentPlayerHp, int attackDmg)
{
currentPlayerHp -= attackDmg;
if (currentPlayerHp <= 0)
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}

The
GetComponent<Enemy>()
is on another object, you can call it if you
1
Create a public variable and add the enemy object
public GameObject enemy;
And then after you dragged your enemy inside it in the inspector you can:
enemy.GetComponent<Enemy>()
Without problems
2
The second thing you can do is just declaring the enemy object
GameObject enemy;
And in the Start() you can
enemy = GameObject.FindGameObjectWithTag("Enemy");
But for this, you need to add a tag in the inspector for the enemy.
After this you can access the enemy as before.

Related

Unity set UI text from other gameobject script C# [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
I have 3 different scripts.
GameController
PlayerController
DestroyOnContact
GameController
public class GameController : MonoBehaviour {
public static Text scoreText;
void Start()
{
StartCoroutine(SpawnWaves());
}
IEnumerator SpawnWaves()
{
yield return new WaitForSeconds(startWait);
while(true)
{
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(hazardSmall, spawnPosition, spawnRotation);
//SpawnHazard();
yield return new WaitForSeconds(spawnWait);
}
}
PlayerController
public static float score = 0;
DestoyOnContact
void OnTriggerEnter(Collider other)
{
if (other.tag == "PlayerBolt")
{
PlayerController.score++;
Debug.Log(PlayerController.score);
GameController.scoreText.text = "Score: " + PlayerController.score;
Debug.Log(GameController.scoreText.text);
}
Destroy(other.gameObject);
Destroy(gameObject);
Problem
When I run my game and shoot the object that uses the DestroyOnContact script, the PlayerController.score++ works and I have debugged it. But trying to set the scoreText in GameController does not work. This results in neither the player shot nor the object being shot destroy.
I get the exception:
NullReferenceException: Object reference not set to an instance of an object
I have tried using:
GameObject gogc = GameObject.Find("GameController");
GameController gc = (GameController)gogc.GetComponent(typeof(GameController));
Followed by:
gc.scoreText.text = "Score: " + PlayerController.score;
Which yields the same result. What am I missing?
Hierarchy:
I would recommend that you don't have the text as a static class as you then can't set it through the inspector.
Instead make a public static instance GameController.
Then in your Awake method of the GameController set instance = this;
You can then call that object by saying GameController.instance.ScoreText.text, remember that your ScoreText should NOT be static.
The reason i put it in the Awake method is to ensure it gets set early in the games lifecycle.
Feel free to ask questions.

Why am i Getting NullReferenceException when trying to create a HealthPack in Unity C#? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Ok guys and gals I'm having an issue again with some code. Basically once I start and it attempts to create a Health Pack it's throwing an error that:
NullReferenceException: Object reference not set to an instance of an object
HealthSpawnerScript.Update () (at Assets/Scripts/HealthSpawnerScript.cs:31)
below is the code i'm running. The gameobject PlayerController houses a method used to return Player Health named PlayerHealth(). In awake I set playerController to find the script and method I'm after. Then in update i'm trying to call the method and assign it to a variable for use in the script later. I know this should be simple but i'm having a brain fart guys.
public PlayerController playerController;
private int healthHolder;
void OnAwake()
{
playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController> ();
}
// Use this for initialization
void Start ()
{
//set healthExist to false to indicate no health packs exist on game start
healthExist = false;
//playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController> ();
}
// Update is called once per frame
void Update ()
{
healthHolder = playerController.PlayerHealth();
There is no Unity callback function named OnAwake. You are likely looking for the Awake function.
If that is fixed and your problem is still there, you have to seperate your code into pieces and find out what's failing.
playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController> ();
should be changed to
void Awake()
{
GameObject obj = GameObject.Find("PlayerHealth");
if (obj == null)
{
Debug.Log("Failed to find PlayerHealth GameObject");
return;
}
playerController = obj.GetComponent<PlayerController>();
if (playerController == null)
{
Debug.Log("No PlayerController script is attached to obj");
}
}
So, if GameObject.Find("PlayerHealth") fails, that means there is no GameObject with that name in the scene. Please check the spellings.
If obj.GetComponent<PlayerController>(); fails, there is no script called PlayerController that is attached to the PlayerHealth GameObject. Simplify your problem!

Input Value Converted To String [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Recently I've been creating a game, and I've been creating a Menu.
At the beginning the player opens the Menu and enters a name into a UI Text Field, which I will convert to a string, so the player may be called that name throughout the storyline.
I've come across another Script on this website:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class GUIFieldTest : MonoBehaviour {
public GameObject playerName;
public void Start ()
{
var input = gameObject.GetComponent<InputField>();
var se = new InputField.SubmitEvent();
se.AddListener(SubmitName);
input.onEndEdit.AddListener(SubmitName);
//or simply use the line below,
//input.onEndEdit = se; // This also works
}
private void SubmitName(string arg0)
{
Debug.Log(arg0);
}
}
I have tweaked this code so I can include a prefab of the Text Field as a GameObject, however I have recieved an error saying:
NullReferenceException: Object reference not set to an instance of an
object GUIFieldTest.Start () (at Assets/Scripts/GUIFieldTest.cs:13)
I understand that this error means that there is nothing assigned, and I understand how to fix the NullReferenceException. I am able to run the game, however the game freezes and the text field is not clickable. You cannot enter any text.
I know this is a very simple question, but it would be great for an explanation.
var input = gameObject.GetComponent<InputField>() should be
var input = playerName.GetComponent<InputField>().
When you use gameObject.GetComponent, it will only find components on the GameObject the script is attached to.
I assume that your InputField GameOBject is the playerName variable.
If this is not true the do var input = GameObject.Find("YourInputFieldGameOBject").GetComponent<InputField>().

I keep getting a error on a script that I am programing the script works but I want to fix the error [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I keep getting this error on a score counter script for a game that I am makingthe score counter works but this error is just annoying and I dont want ot publish it with the errors stacking up.
Error:
NullReferenceException: Object reference not set to an instance of an object
ScoreCounter.Update () (at Assets/ScoreCounter.cs:26)
Script:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreCounter : MonoBehaviour
{
public static int score; // The player's score.
public Text text; // Reference to the Text component.
void Start ()
{
// Set up the reference.
//text = GetComponent <Text> ();
// Reset the score.
score = 0;
}
void Update ()
{
// Set the displayed text to be the word "Score" followed by the score value.
text.text = "Score:" + score;
}
}
From the error message it's very clear that your text object is never instantiated.
I don't know enough about your use-case to recommend where it should be instantiated, but inside of Start() looks like a good place.
Cheers

Unity FPS Game Error [duplicate]

This question already has answers here:
Bullet Prefab Script
(3 answers)
Closed 8 years ago.
I am getting an error in this script.
UnityEngine does not contain a definition for rigidbody (Lines: 22,24)
public class GunShoot : MonoBehaviour
{
public GameObject BulletPrefab;
public float BulletSpeed;
public int BulletsInClip;
public AudioClip GunshotSound;
void Update () {
if (Input.GetButtonDown("Shoot")){
Shoot();
}
}
void Shoot() {
var bullet = Instantiate(BulletPrefab, transform.Find("BulletSpawn").position, transform.Find("BulletSpawn").rotation);
bullet.rigidbody.AddForce(transform.forward * BulletSpeed);
audio.PlayOneShot(GunshotSound);
BulletsInClip--;
}
}
Please tell me what to edit instead of just editing the script.
Your call to Instantiate() doesn't result in a GameObject. It will return a plain Object. So subsequently you're trying to access the RigidBody - using bullet.rigidbody - which an Object has no knowledge about.
When instantiating therefore perform an explicit cast:
var bullet = (GameObject) Instantiate(BulletPrefab, transform.Find("BulletSpawn").position, transform.Find("BulletSpawn").rotation);
Or even explicitly write GameObject bullet = ... to avoid errors like this. If you do, the compiler will start to complain at the location of the true error if you forget the cast.

Categories