I am trying to pass on a value from OnTriggerEnter function for a class to another class.I already set the value that I want to pass to global variable.This is how I do :
public GameObject go;
public bool isSomething;
public static AClass instance;
public void Start()
{
instance=this;
}
public void OnTriggerEnter(Collision other)
{
if(go.tag=="Something")
{
isSomething=true;
}
}
The problem is at another class,I call isSomething from AClass and I run the Unity,it give me NullExceptionReference when I pass through a game object.This is the another class code :
private AClass aclass;
public void Start()
{
aclass=AClass.instance;
}
public void Update()
{
Debug.Log(aclass.isSomething); //<-----------------This give Null Exception Reference
}
I want to get a value just after I pass a collider trigger and not before passing a collider trigger.I don't know is this a dumb question but I hope someone can give me some idea.Thanks. :)
Try assigning the instance in the Awake function:
public void Awake()
{
instance = this;
}
There's no guarantee that the Start() function of one object happens before or after that of another object unless you explicitly set the execution order.
This code is wrong.
public void OnTriggerEnter(Collision other)
{
if(go.tag=="Something")
{
isSomething=true;
}
}
Solution
public void OnTriggerEnter(Collision other)
{
if(other.tag == "Something")
isSomething=true;
}
Related
I have problem because I can't read a static value added to Uptade() and use it.
Rock
[Header("Points")]
public TextMeshProUGUI points;
public static int point;
private void Start()
{
points = GetComponent<TextMeshProUGUI>();
}
void Update()
{
Move();
}
void Move()
{
point += 1;
Debug.Log(point);
}
Points
[Header("Points")]
public TextMeshProUGUI points;
public Rock countPoint;
void Start()
{
}
void Update()
{
Debug.Log("points" + countPoint.point);
}
I want to see this point in class points. If i will delete static then debug showing just 0.
Can you show me how to do it in correct way in full example ? or reedit my code.
You're trying to access a static member by using an object reference.
Instead of using an instance of the object:
Debug.Log("points" + countPoint.point);
You should be using using the class to call the field:
Debug.Log("points" + Rock.point);
Static variables/functions can directly be accessed by class name.
So, Rock.point would do.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 months ago.
I working through an online lesson and getting a Null reference exception. I know it's an extremely common error but neither I or the online help for the course have been able to figure it out. So I'm hoping for some insight here.
Level Manager Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelManager : MonoBehaviour
{
[SerializeField] float sceneLoadDelay = 2f;
ScoreKeeper scoreKeeper;
void Start()
{
scoreKeeper = FindObjectOfType<ScoreKeeper>();
}
public void LoadGame()
{
scoreKeeper.ResetScore();
SceneManager.LoadScene("MainGame");
}
public void LoadMainMenu()
{
SceneManager.LoadScene("MainMenu");
}
public void LoadGameOver()
{
StartCoroutine(WaitAndLoad("GameOver", sceneLoadDelay));
}
public void QuitGame()
{
Debug.Log("Quitting Game...");
Application.Quit();
}
IEnumerator WaitAndLoad(string sceneName, float delay)
{
yield return new WaitForSeconds(delay);
SceneManager.LoadScene(sceneName);
}
}
Score Keeper Script:
public class ScoreKeeper : MonoBehaviour
{
int score;
static ScoreKeeper instance;
void Awake()
{
ManageSingleton();
}
void ManageSingleton()
{
if (instance != null)
{
gameObject.SetActive(false);
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
public int GetScore()
{
return score;
}
public void ModifyScore(int value)
{
score += value;
Mathf.Clamp(score, 0, int.MaxValue);
Debug.Log(score);
}
public void ResetScore()
{
score = 1;
}
}
Error is in the level manager at this line: scoreKeeper.ResetScore();
I should add that the a Level Manager and a Score Keeper Object were created with the scripts attached and are in each scene.
In the Hierarchy look for at least 2 GameObjects present or not
One with ScoreKeeper.cs attached
Another with LevelManager.cs attached
If this is ok then open LevelManager.cs and add private keyword before the line ScoreKeeper scoreKeeper; as you are already finding and attaching it in Start() method, like this below
private ScoreKeeper scoreKeeper;
The issue is that you need to call ScoreKeeper.instance.ResetScore(). You have it setup as a singleton. Otherwise you will need to add a concrete reference to an instance in your level manager.
You also need to make the instance public:
public static ScoreKeeper instance;
I'm trying to make a simple damage boost I have 2 scripts, one attached to the projectile and one to the booster
Projectile:
public class DamageDealer : MonoBehaviour
{
[SerializeField] public int damage = 25;
public int GetDamage()
{
return damage;
}
public void Hit()
{
Destroy(gameObject);
}
public void IncreaseDamage(int value)
{
damage += value;
Mathf.Clamp(damage, 0, int.MaxValue);
}
}
Booster:
public class DamageUp : MonoBehaviour
{
int damageBoost = 50;
DamageDealer damageDealer;
void Awake()
{
damageDealer = FindObjectOfType<DamageDealer>();
Debug.Log(damageDealer); // this returns as null
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
damageDealer.IncreaseDamage(damageBoost);
}
}
}
As you can see in the Booster I've already identified what's returning as null, but I'm quite new to unity and C# so I don't know what I'm doing wrong
Some more info the Projectile is a prefab while the Booster is not (yet)
scripts are attached and enabled, objects are enabled too.
Hit() and GetDamage() are for another script I have no issue with.
Thanks in advance.
You're probably trying to find the object before it's instantiated, change the Awake to Start or try to change Script Execution Order settings
Check Also; Order of execution for event functions
Good Day all, I am trying to make a simple 2D game and here is how it works. Assume there is a sprite "tent", and whenever i clicked the tent, the console will print out a message. Sounds straightforward is it? However I'm like stuck in the middle of it and I know I am gonna facepalmed myself so hard after this. What I did in my script is:
public abstract class Player : MonoBehaviour {
protected string _name;
// Use this for initialization
public Player(string name)
{
_name = name;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
void Start () {
}
// Update is called once per frame
void Update () {
}}
Next I have a child class called Civilian
public class Civilian : Player {
// Use this for initialization
public Civilian(string name):base(name)
{
}
void Start () {
}
// Update is called once per frame
void Update () {
}
}
Then in my script "Tentclicked", i want to called the function of sleep when the sprite is clicked.
public class tentclicked : MonoBehaviour {
void OnMouseDown()
{
// c.Sleep();
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
And you are wondering what is c and what it is point to? I instantiated a new class in another script called testing1.
public class testing1 : MonoBehaviour
{
public Text p1name;
public void Awake()
{
//p1name.text = "Hello";
//Civilian C = Scriptss.AddComponent<Civilian>();
//GameObject theCivilian = GameObject.Find("Scriptss");
// Civilian c = theCivilian.GetComponent<Civilian>();
//c.Name = Testingsavename.playernames.username;
//c.Name = "Hello";
}
// Use this for initialization
void Start()
{
if (Choosechar.choice.choicecount == 1)
{
Civilian c = new Civilian(Testingsavename.playernames.username);
p1name = GetComponent<Text>();
p1name.text = c.Name;
}
I have already add a circle collider to my sprite. The error is that in tentclicked, c does not exist in context. So i suspect it may be that unity does not know what c is. I am thinking of making civilian class a static one, and just called Civilian.civilian.Sleep() in tentclicked script....
"c" does not exist in this context because your tentclicked class has no reference to it. Find "c" with GameObject.Find(string name) and assign the gameobject value to a variable in tentclicked
You could raycast from the current mouse position towards the object (just make sure that the object has a collider.
void OnMouseDown()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if ( Physics.Raycast (ray,out hit,100.0f))
{
Civilian c = hit.collider.gameObject.GetComponent<Civilian>();
c.Sleep();
}
}
How can I make an object invisible (or just delete) after a certain period of time?
Use NGUI.
My example (for changes):
public class scriptFlashingPressStart : MonoBehaviour
{
public GameObject off_Logo;
public float dead_logo = 1.5f;
void OffLogo()
{
off_Logo.SetActive(false);
}
//function onclick button
//remove item after a certain time after pressing ???
void press_start()
{
InvokeRepeating("OffLogo", dead_logo , ...);
}
}
Use Invoke rather than InvokeRepeating.
check Invoke function here
public class scriptFlashingPressStart : MonoBehaviour
{
public GameObject off_Logo;
public float dead_logo = 1.5f;
bool pressed = false;
void OffLogo()
{
//do anything(delete or invisible)
off_Logo.SetActive(false);
pressed = false;
}
//use Invoke rather than InvokeRepeating
void press_start()
{
if(!pressed)
{
pressed = true;
Invoke("OffLogo", dead_logo);
}
else
{
Debug.Log("Button already pressed");
}
}
}
try
StartCoroutine(SomeFunctionAfterSomeTime);
IEnumerator SomeFunctionAfterSomeTime()
{
... //Your own logic
yield return new WaitForSeconds(SomeTime);
}
You can destroy an object in a given time by simply calling Destroy.
public static void Destroy(Object obj, float t = 0.0F);
Parameters
obj The object to destroy.
t The optional amount of time to delay
before destroying the object.
See http://docs.unity3d.com/Documentation/ScriptReference/Object.Destroy.html