Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
869 views
in Technique[技术] by (71.8m points)

unity3d - Unity C# Null Reference Exception

I am trying to get data from an int variable in Unity using C# code. Below is the C# code I am using to get the int.

using UnityEngine;
using System.Collections;

public class endGameMessage : MonoBehaviour {
public static int score2;

void Start () {
    GameObject thePlayer = GameObject.FindWithTag("Player");
    gameScript game = thePlayer.GetComponent<gameScript>();
    score2 = game.score;
}

// Update is called once per frame
void Update () {

    Debug.Log (score2);

}
}

Below is the code from the other script I am trying to pull the data from.

using UnityEngine;
using System.Collections;

public class gameScript : MonoBehaviour {
//score
public int score = 0;
void OnTriggerEnter(Collider other) {
    if(other.gameObject.tag =="hammer"){
        GameObject.FindGameObjectWithTag("pickUpMessage").guiText.text = ("Picked Up A Hammer");    

        Destroy(other.gameObject);
        Debug.Log("collision detected hammer");
        audio.PlayOneShot(gotHit);
        score = score+10;
    }
     }
}

I can get the the int value to come across to the other script but its always 0 even if the int was meant to be 10.

My question is how would i keep the value across the scripts? Any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

try this

public static int score2
{
    get
    {
        return GameObject.FindWithTag("Player").GetComponent<gameScript>().score;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...