Changing sprite frame on mouseEnter in Unity [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have an assets file under the name of play-button with texture type=sprite2D and Sprite Mode = Multiple, it contains 2 different frames: play-button0 and play-button1
i have attached a c# script file for this asset with the following code:
using UnityEngine;
using System.Collections;
public class Play_btn : MonoBehaviour {
SpriteRenderer spriteRenderer;
Sprite s1;
Sprite s2;
// Use this for initialization
void Start () {
spriteRenderer = GetComponent<SpriteRenderer>();
if (spriteRenderer.sprite == null)
spriteRenderer.sprite = s1;
}
void OnMouseDown() {
Application.LoadLevel("Levels");
}
void OnMouseEnter() {
spriteRenderer.sprite = s2;
}
void OnMouseExit() {
//spriteRenderer.sprite = sprite1;
}
// Update is called once per frame
void Update () {
}
}
As you can see i am trying to change the frame onMouseEnter and OnMouseExit but when the mouseEnter the play button a null reference error is occurring and a blank object is displaying on the screen, can anyone help me in this problem?

From what I see, the Sprites s1 & s2 are not public (so you could not have assigned it via the inspector), and there's no code where you assign the s1 & s2 variables.
Solution
Make the Sprites s1 and s2 public, and assign them.

Related

How to read a variable from another script in Unity [duplicate]

This question already has answers here:
How to access a variable from another script in another gameobject through GetComponent?
(3 answers)
Closed 25 days ago.
I want that when the player have low health, a red screen (already did a loop animation for it) with an animation plays (it plays automatically that's why im just activating the gameObject),I tried to do it with saving the value in a text file and read it from the other script, but is not optimized and it doesn't work, what it looks like :
public void CreateText()
{
string path = Application.dataPath + "/Datas/data";
if (!File.Exists(path))
{
File.WriteAllText(path, "" + health);
}
else
{
File.Delete(path);
File.WriteAllText(path, "" + health);
}
}
In the other Script :
public int health = 1000;
public string health0;
public string path = Application.dataPath + "/Datas/data";
public GameObject healthbar;
void Update()
{
Int32.TryParse(health0, out health);
File.ReadLines(path);
if (health <= 600)
{
healthbar.SetActive(true);
}
else
{
if (healthbar.activeInHierarchy == true)
{
healthbar.SetActive(false);
}
}
}
You can access scripts from other scripts just by getting the script component (like any other component). Lets say you have a game object A with an attached script ScriptA and also a game object B with a script ScriptB. To access ScriptB from ScriptA, you would need to:
class ScriptA : Monobehaviour {
void Method() {
GameObject b = GameObject.Find("B"); // get somehow a reference to B
ScriptB scriptB = b.GetComponent<ScriptB>(); // get access to the script
// now you can access all public stuff from the script
scriptB.publicAttribute ...
scriptB.publicMethod() ...
}
}
For such runtime logic like you have with the healthbar, you should not use the filesystem. This is really an unnecessary detour.

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.

Accessing a variable from another script C# UNITY [duplicate]

This question already has answers here:
How to access a variable from another script in another gameobject through GetComponent?
(3 answers)
Closed 6 years ago.
I have two script
simplecloudhander.cs
cloudtarget.cs
simplecloudhander.cs
public string mTargetMetadata = "";
public void OnNewSearchResult(TargetFinder.TargetSearchResult targetSearchResult)
{
GameObject newImageTarget = Instantiate(ImageTargetTemplate.gameObject) as GameObject;
GameObject augmentation = null;
string model_name = targetSearchResult.MetaData;
if( augmentation != null )
augmentation.transform.parent = newImageTarget.transform;
ImageTargetAbstractBehaviour imageTargetBehaviour = mImageTracker.TargetFinder.EnableTracking(targetSearchResult, newImageTarget);
Debug.Log("Metadata value is " + model_name );
mTargetMetadata = model_name;
}
i want to access mTargetMetadata value in another cloudtarget.cs script
here cloudtarget.cs script
void OnGUI() {
SimpleCloudHandler sc = new SimpleCloudHandler ();
GUI.Label (new Rect(100,300,300,50), "Metadata: " + sc.mTargetMetadata);
}
but i can't get mTargetMetadata value in another script
You have to add a reference to that script in the cloudtarget script. Just add a public variable of type SimpleCloudHandler to the class cloudtarget, not on the OnGUI method, later drag and drop the GameObject with the SimpleCloudHandler atached to the script cloudtarget in the inspector.
Example:
Drag and drop the MainCamera with the SimpleCloudHandler script attached => to the public SimpleCloudHandler variable of the cloudtarget script through the inspector.
There are multiple ways to make a reference in Unity, I recommend you to look to the documentation that Unity offer
if your scripts are attached to the same object then you can use GetComponentlike this,
gameObject.GetComponent<simplecloudhander>().mTargetMetadata
if they are not attached to the same gameObjectthe you can use GameObject.Find first to find the gameObject that the script is attached to, you should use the name of the gameObject to find it, then use the GetComponent to get the componentthat you want
GameObject.Find("nameOftheGameObject").GetComponent<simplecloudhander>().mTargetMetadata
also there is no need for new keyword, if you just want to access it,
simplecloudhander sch;
void Start()
{
sch = GameObject.Find("nameOftheGameObject").GetComponent<simplecloudhander>();
}
void OnGUI() {
GUI.Label (new Rect(100,300,300,50), "Metadata: " + sch .mTargetMetadata);
}

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>().

Categories