Unity3D getting a NullReferenceException for a split second - unity3d

As the title says. I'm getting a NullReferenceException for a split second, and after that, everything Works just fine. Could anyone tell me why this happens?
Here's my code, error's from line 43:
#pragma strict
//NOTE: Display the health of the enemy that is targetted by the player!
//private var enemyGO : GameObject;
//private var enemyScript : EnemyAI;
var healthText : GUIText;
var myPlayer : Transform;
var myPlayerScript : PlayerScript;
var myPlayerTarget : Transform;
var myPlayerTargetScript : EnemyAI;
function Start () {
myPlayer = GameObject.FindGameObjectWithTag("Player").transform;
myPlayerScript = myPlayer.GetComponent("PlayerScript");
/* if (myPlayerScript.target != null) {
myPlayerTarget = myPlayerScript.target;
myPlayerTarget.GetComponent("EnemyAI");
}*/
// enemyGO = GameObject.Find("Enemy");
// enemyScript = enemyGO.GetComponent("EnemyAI");
}
function FixedUpdate () {
if (myPlayerScript.target != null) {
myPlayerTarget = myPlayerScript.target;
myPlayerTargetScript = myPlayerTarget.GetComponent("EnemyAI");
}
}
function OnGUI () {
if (myPlayerScript.target != null) {
GUI.Label (Rect (((Screen.width / 2) + Screen.width / 3), 16, 250, 20), "EnemyHP: " + (Mathf.Round(myPlayerTargetScript.curHealth)) + " / " + /*(Mathf.Round(*/myPlayerTargetScript.maxHealth/*))*/);
}
}
Thank you :)
EDIT: This doesn't show lines :P
So the error is happening in the GUI.Label... line in my OnGUI function :)

Since you already hold a reference to your EnemyAI script in myPlayerTargetScript you should check this for null in OnGUI
Also don't use FixedUpdate for such things. FixedUpdate belongs to the physics system. Just use Update instead:
#pragma strict
var healthText : GUIText;
var myPlayer : Transform;
var myPlayerScript : PlayerScript;
var myPlayerTarget : Transform;
var myPlayerTargetScript : EnemyAI;
function Start () {
myPlayer = GameObject.FindGameObjectWithTag("Player").transform;
myPlayerScript = myPlayer.GetComponent(PlayerScript);
}
function Update () {
if (myPlayerScript.target != null) {
myPlayerTarget = myPlayerScript.target;
myPlayerTargetScript = myPlayerTarget.GetComponent(EnemyAI);
}
}
function OnGUI () {
if (myPlayerTargetScript != null) {
GUI.Label (Rect (((Screen.width / 2) + Screen.width / 3), 16, 250, 20), "EnemyHP: " + (Mathf.Round(myPlayerTargetScript.curHealth)) + " / " + myPlayerTargetScript.maxHealth);
}
}
ps: You should tidy up your script before posting it here ;)

Related

Expressions in statements must only be executed for their side effects

I'm having a rather unusual problem with this code in unity, I keep getting the error "Expressions in statements must only be executed for their side-effects", I went around the web searching for the problem but all the answers were different, the line that is giving the error is (47,44) which is the AnimObj.GetComponent.<Animation>().Play thanks in advance for the help -_-;
var CrossObject : GameObject;
var MechanicsObject : GameObject;
var ClipCount : int;
var ReserveCount : int;
var ReloadAvailable : int;
var AnimObj : GameObject;
var ScriptObj : GameObject;
function Update () {
ClipCount = GlobalAmmo.LoadedAmmo;
ReserveCount = GlobalAmmo.CurrentAmmo;
if (ReserveCount == 0) {
ReloadAvailable = 0;
} else {
ReloadAvailable = 10 - ClipCount;
}
if (Input.GetButtonDown("Reload")) {
if (ReloadAvailable >=1) {
if (ReserveCount <= ReloadAvailable) {
GlobalAmmo.LoadedAmmo += ReserveCount;
GlobalAmmo.CurrentAmmo -= ReserveCount;
ActionReload();
} else {
GlobalAmmo.LoadedAmmo += ReloadAvailable;
GlobalAmmo.CurrentAmmo -= ReloadAvailable;
ActionReload();
}
}
EnableScripts();
}
}
function EnableScripts () {
yield WaitForSeconds(1);
ScriptObj.GetComponent("Fire").enabled=true;
CrossObject.SetActive(true);
MechanicsObject.SetActive(true);
}
function ActionReload () {
ScriptObj.GetComponent("Fire").enabled=false;
CrossObject.SetActive(false);
MechanicsObject.SetActive(false);
AnimObj.GetComponent.<Animation>().Play;
}
In Unity, Animation.Play() is a function not a variable. You are accessing that as a variable by not including () at the end of Play.
It should be:
AnimObj.GetComponent.<Animation>().Play();

Score isn't showing in guiText

I have guiTexts called scoreLevel1, scoreLevel2 where i want to show the score from the right levels but it isn't showing any text or scores... There are no build errors. How do I make it show up as expected?
var Score : int;
function Update () {
Score -= 1 * Time.deltaTime;
guiText.text = "Score: "+Score;
TimerOfDeath();
}
HighScores.js:
//run at start if score doesn't exist yet to initialise playerPref
function Start(){
if(!PlayerPrefs.HasKey(Application.loadedLevelName+"HighScore"))
PlayerPrefs.SetFloat(Application.loadedLevelName+"HighScore", 0);
}
//run when level is completed
function OnTriggerEnter(other : Collider){
if(other.tag == "Player"){
Score = gameObject.Find("ScoreCount").GetComponent("ScoringPts").Update("Score");
if(Score > PlayerPrefs.GetFloat(Application.loadedLevelName+"HighScore"))
{
PlayerPrefs.SetFloat(Application.loadedLevelName+"HighScore", Score);
}
}
}
GetHighScores.js:
#pragma strict
function Start () {
var hscount = 1;
var iterations = 1;
var maxIterations = 5;
var findtext = gameObject.Find("scoreLevel"+(hscount));
while(hscount < 5 && iterations < maxIterations){
if(!PlayerPrefs.HasKey("Level"+(hscount)+"HighScore")){
findtext.guiText.text = "Level"+(hscount)+ ": " + PlayerPrefs.GetFloat("Level"+(hscount)+"HighScore");
hscount++;
}
iterations++;
}
}

How make a Level Unlocker using GUI Buttons and PlayerPrefs things?

#pragma strict
var challenge1 : Texture;
var challenge2 : Texture;
var challenge3 : Texture;
var LevelOneEnabled = true;
var LevelTwoEnabled = false;
var LevelThreeEnabled = false;
var Score : TextMesh;
var Score2 : TextMesh;
var Score3 : TextMesh;
function Start(){
}
function Awake(){
Score.text = "Highscore: "+ PlayerPrefs.GetInt("JeepneyScore");
Score2.text = "Highscore: "+ PlayerPrefs.GetInt("JeepneyScore2");
Score3.text = "Best Time: "+ PlayerPrefs.GetFloat("JeepneyScore3");
}
function OnGUI()
{
GUI.enabled = LevelOneEnabled;
if(GUI.Button(Rect(400,100,250,250),challenge1)){
Application.LoadLevel("LoadScene");
}
GUI.enabled = LevelTwoEnabled;
if(GUI.Button(Rect(700,100,250,250),challenge2)){
Application.LoadLevel("LoadScene2");
}
GUI.enabled = LevelThreeEnabled;
if(GUI.Button(Rect(1000,100,250,250),challenge3)){
Application.LoadLevel("LoadScene3");
}
}
Can anybody knows hot to get the logic in playerprefs so that the LoadScene2, and 3
will unlock after finishing the first mission?
Please I'm hoping for an answer :(
put in
var level : int;
then in start
level = PlayerPrefs.GetInt("level",0);
then in your if(GUI.Buttons){}
if(level >= 2){}
and
if(level >= 3){}
and so on and in your actual levels set the int in your playerprefs once they complete the level, probably load the int again and use if to check if it is greater than then replace if it is not
EDIT:
var levelnum : int = 2;
PlayerPrefs.SetInt("level",levelnum);

Implicit downcast from 'UnityEngine.Component[]' to 'UnityEngine.ParticleEmitter[]'

#pragma strict
static var charge : int = 0;
var collectSound : AudioClip;
//HUD
var hudCharge : Texture2D[];
var chargeHudGUI : GUITexture;
//Generator
var meterCharge : Texture[];
var meter : Renderer;
//Matches
private var haveMatches : boolean = false;
var matchGUIprefab : GUITexture;
private var matchGUI : GUITexture;
var fireEmitters : ParticleEmitter[];
var TextHints : GUIText;
function Start ()
{
charge = 0;
}
function Update ()
{
}
function CellPickup()
{
AudioSource.PlayClipAtPoint(collectSound, transform.position);
charge++;
chargeHudGUI.texture = hudCharge[charge];
meter.material.mainTexture = meterCharge[charge];
HUDon();
}
function HUDon()
{
if(!chargeHudGUI.enabled)
{
chargeHudGUI.enabled = true;
}
}
function MatchPickup()
{
haveMatches = true;
AudioSource.PlayClipAtPoint(collectSound, transform.position);
var matchHUD : GUITexture = Instantiate(matchGUIprefab, Vector3(0.15,0.1,0),transform.rotation);
matchGUI = matchHUD;
}
function OnControllerColliderHit(col : ControllerColliderHit)
{
if(col.gameObject.name == "campfire")
{
if(haveMatches)
{
LightFire(col.gameObject);
}
else
{
TextHints.SendMessage("ShowHint", "i could use this campfire to signal for help... \n if only i could light it");
}
}
}
function LightFire(campfire : GameObject)
{
fireEmitters = campfire.GetComponentsInChildren(ParticleEmitter);
for(var emitter : ParticleEmitter in fireEmitters)
{
emitter.emit = true;
}
campfire.audio.Play();
Destroy(matchGUI);
haveMatches=false;
}
i was 1st having a problem saying can't cast from source type to destination type then i added pragma strict and now i'm getting the error in the title, now i'm writing more because the lovely website thinks that that didn't explain enough.
Ok, I'm not familiar with this apparently typed variant of javascript, but assuming it's something like the other Java-family languages and has C-style casts, I would try this in LightFire:
var emitters : Component[] = campfire.GetComponentsInChildren(ParticleEmitter);
for(var emitter : Component in fireEmitters)
{
((ParticleEmitter)emitter).emit = true;
}
If that's not the right syntax, then find out how to do a downcast.

Doing an Highscore table

I'm trying to create a Highscore table for my Arcade spaceshooter game, im doing this table with variables so no DB is needed to store the scores they will be temporary
var high1 : int;
var high2 : int;
var high3 : int;
var high4 : int;
var high5 : int;
function OnGUI () {
var camera;
camera = GameObject.FindWithTag("MainCamera");
var scorepoints;
scorepoints = camera.GetComponent(Scorescript).currentScore;
}
I'm using Unity btw and im trying to access the Scorescript which harbors the current score the Player had, problem is it always says it cant find the component of the script,the object tag name is right and the script name too, here is the score script:
var customSkin : GUISkin;
var enemy;
enemy = GameObject.FindWithTag("Enemy");
var currentScore : int = 0;
var visibleScore : int = 0;
function OnGUI () {
GUI.skin = customSkin;
GUILayout.BeginArea ( Rect ( Screen.width / 1.2, Screen.height / 10 ,300,200) );
GUILayout.Box ( visibleScore.ToString () );
GUILayout.EndArea ();
}
function AnimateVisibleScore () {
iTween.ValueTo (
gameObject,
{
"from" : visibleScore,
"to" : currentScore,
"onupdate" : "ChangeVisibleScore",
"time" : 0.5
}
);
}
function ChangeVisibleScore ( i : int ) {
visibleScore = i;
}
function IncrementScore ( i : int ) {
currentScore += i;
AnimateVisibleScore ();
}
function DecrementScore ( i : int ) {
currentScore -= i;
AnimateVisibleScore ();
}
And I'm a nublet at scripting if anyone could give a hand in finishing this particular part i would be very grateful.
Try
scorepoints = Camera.main.GetComponentInChildren("Scorescript");