• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by carter-carl30 · May 21, 2013 at 10:48 PM · javascriptcharactercontrollernoobrespawnspawnpoint

help with character respawn after death (javascript)

Hi all, I am using this script (under this text) for a 2D platform game (my knowledge of programming is very limited). What I am trying to do is make the player respawn after death.

character controller script:

     public var skin : GUISkin;                        //GUI skin
     public var mesh : GameObject;                    //Mesh
     public var texMove : Texture2D[];                //Move texture
     public var texJump : Texture2D;                    //Jump texture
     public var audioJump : AudioClip;                //Jump sound
     public var audioDead : AudioClip;                //Dead sound
     private var selectedTex : int;                    //Selected texture
     public var texUpdateTime : float;                //Texture update time
     private var tmpTexUpdateTime : float;            //Tmp texture update time
     public var moveSpeed : float;                    //Move speed
     public var jumpSpeed : float;                    //Jump speed
     public var gravity : float;                        //Gravity
     private var dir : Vector3;                        //The direction the player is movin
     private var rightTouchPad : GameObject;            //Right touchpad
     private var leftTouchPad : GameObject;            //Left touchpad
     var dead = false;                        //Are we dead
     private var controller : CharacterController;    //The character controller
     
     function Start ()
     {
         //Find the character controller
         controller = GetComponent(CharacterController);
         //Screen orientation to landscape left
         Screen.orientation = ScreenOrientation.LandscapeLeft;
         //Find left touchpad
         leftTouchPad = GameObject.Find("LeftTouchPad");
         //Find right touchpad
         rightTouchPad = GameObject.Find("RightTouchPad");
         //Start SetupJoysticks
         StartCoroutine("SetupJoysticks");
         //Set sleep time to never
         Screen.sleepTimeout = SleepTimeout.NeverSleep;
     }
     
     function Update ()
     {
         //If we are not dead
         if (!dead)
         {
             //Update
             MoveUpdate();
             TexUpdate();
         }
     }
     
     function MoveUpdate()
     {
         //If we hit a object
         var hit : RaycastHit;
         if (Physics.Raycast(transform.position, Vector3.up, hit, 0.5f))
         {
             //If it is not the player
             if (hit.transform.gameObject.tag != "Player")
             {
                 //Set dir y to -1
                 dir.y = -1;
             }
         }
         
         //If we are grounded
         if (controller.isGrounded)
         {
             //If the game is not running on a android device
             if (Application.platform != RuntimePlatform.Android)
             {
                 //Set dir x to Horizontal
                 dir.x = Input.GetAxis("Horizontal") * moveSpeed;
                 //If we get Space key down
                 if (Input.GetKeyDown(KeyCode.Space))
                 {
                     //Set dir y to jumpSpeed
                     dir.y = jumpSpeed;
                     //Play jump sound
                     audio.clip = audioJump;
                     audio.Play();
                 }
             }
             //If the game is running on a android device
             else
             {
                 //Get left touchpad position x
                 var pX = leftTouchPad.GetComponent(Joystick).position.x;
                 //Get left touchpad tap count
                 var tC = rightTouchPad.GetComponent(Joystick).tapCount;
                 
                 //Set dir x to touchpad x position
                 dir.x = pX * moveSpeed;
                 //If touchpad tap count are not 0
                 if (tC != 0)
                 {
                     //Set dir y to jumpSpeed
                     dir.y = jumpSpeed;
                     //Play jump sound
                     audio.clip = audioJump;
                     audio.Play();
                 }
             }
         }
         //If we are not grounded
         else
         {
             //Set dir y to gravity
             dir.y -= gravity * Time.deltaTime;
         }
         
         //Move the player
         controller.Move(dir * Time.smoothDeltaTime);
     }
     
     function TexUpdate()
     {
         //If we are not grounded
         if (!controller.isGrounded)
         {
             //Set main texture to jump texture
             mesh.renderer.material.mainTexture = texJump;
             return;
         }
         //If the game is not running on a android device
         if (Application.platform != RuntimePlatform.Android)
         {
             //Get Horizontal
             var h = Input.GetAxis("Horizontal");
             //If Horizontal is not 0
             if (h != 0)
             {
                 //If Horizontal is bigger than 0
                 if (h > 0)
                 {
                     //Set scale to 1,1,1
                     mesh.transform.localScale = Vector3(1,1,1);
                 }
                 //If Horizontal is less than 0
                 else
                 {
                     //Set scale to -1,1,1
                     mesh.transform.localScale = Vector3(-1,1,1);
                 }
             }
             //If Horizontal is 0
             else
             {
                 //Set main texture to move texture
                 mesh.renderer.material.mainTexture = texMove[0];
                 return;    
             }
         }
         //If the game is running on a android device
         else
         {
             //Get left touchpad x position
             var pX = leftTouchPad.GetComponent(Joystick).position.x;
             //If touchpad x position is not 0
             if (pX != 0)
             {
                 //If touchpad x position is bigger than 0
                 if (pX > 0)
                 {
                     //Set scale to 1,1,1
                     mesh.transform.localScale = Vector3(1,1,1);
                 }
                 //If touchpad x position is less than 0
                 else
                 {
                     //Set scale to -1,1,1
                     mesh.transform.localScale = Vector3(-1,1,1);
                 }
             }
             else
             {
                 //Set main texture to move texture
                 mesh.renderer.material.mainTexture = texMove[0];
                 return;    
             }
         }
         
         //If tmpTexUpdateTime is bigger than texUpdateTime
         if (tmpTexUpdateTime > texUpdateTime)
         {
             //Set tmpTexUpdateTime to 0
             tmpTexUpdateTime = 0;
             //Add one to selectedTex
             selectedTex++;
             //If selectedTex si bigger than texMove.Length - 1
             if (selectedTex > texMove.Length - 1)
             {
                 //Set selectedTex to 0
                 selectedTex = 0;
             }
             //Set main texture to move texture
             mesh.renderer.material.mainTexture = texMove[selectedTex];
         }
         else
         {
             //Add 1 to tmpTexUpdateTime
             tmpTexUpdateTime += 1 * Time.deltaTime;
         }
     }
     
     function OnTriggerEnter(other : Collider)
     {
         //If we are in a enemy trigger
         if (other.tag == "Enemy")
         {
             //Play dead sound
             audio.clip = audioDead;
             audio.Play();
             //Dont show renderer
             mesh.renderer.enabled = false;
             //Kill
             dead = true;
         }
     }
     
 //    function OnGUI()
 //    {
 //        GUI.skin = skin;
 
         //Menu Button
 //        if(GUI.Button(new Rect(Screen.width - 120,0,120,40),"Menu"))
 //        {
 //            Application.LoadLevel("Menu");
 //        }
         //If we are dead
 //        if (dead)
 //        {
             //Play Again Button
 //            if(GUI.Button(new Rect(Screen.width / 2 - 90,Screen.height / 2 - 60,180,50),"Play Again"))
 //            {
 //                Application.LoadLevel("Game 3");
 //            }
             //Menu Button
 //            if(GUI.Button(new Rect(Screen.width / 2 - 90,Screen.height / 2,180,50),"Menu"))
 //            {
 //                Application.LoadLevel("Menu");
 //            }
 //        }    
 //    }
     
     function SetupJoysticks()
     {
         //Set touchpad position
         leftTouchPad.transform.position = Vector3(0,0,0);
         rightTouchPad.transform.position = Vector3(1,0,0);
         
         //Wait 1 second
         yield WaitForSeconds(1);
         
         //Start the touchpads
         leftTouchPad.GetComponent(Joystick).StartGame();
         rightTouchPad.GetComponent(Joystick).StartGame();
     }

I don't know how to alter this script to achieve this without messing up the character controller.

I have tried to write a respawn script (using answers from this site) this is what I have come up with (try not to laugh!):

 static var Counter : int = 0;
 var respawn : Transform;
 var Ninja : GameObject;
 
 function Update () {
 
 var dead : GameObject = GameObject.FindWithTag("goal"); //more efficient than Find
 var script : Game3_Player = dead.GetComponent(Game3_Player); //get script instance
 if(script.dead) {
 
 Respawn();
 
 }
 }
 
 function Respawn(){
 
 //wait for 1 second
 yield WaitForSeconds(1);
 
 //take a life off lives
 lives_counter.Counter =-1;
 
 //spawn Player at spawnpoint
 Instantiate(Ninja, respawn.transform.position, respawn.transform.rotation);
 
 //print msg for debugging
 Debug.Log("respawned");
 
 }

I have this respawn script attached to an empty game object "script_manager", in the inspector on this script i have respawn populated with my spawnpoint, and ninja populated with my player (which is tagged with "goal" tag), (character controller) object.

when I play and walk into the enemy my player dies but doesn't respawn and I'm getting this error:-

NullReferenceException: Object reference not set to an instance of an object respawn_after_death_script.Update () (at Assets/Game 3/Script/Javascript/respawn_after_death_script.js:9)

any help or advice would be appriciated, thankyou

Comment

People who like this

0 Show 0
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image

Answer by ricardo_arango · May 21, 2013 at 11:06 PM

In general, an exception is thrown (http://msdn.microsoft.com/en-us/library/5b2yeyab.aspx) when something unexpected happens.

A NullReferenceException is thrown when a a program tries to access (use) a reference to an object, but the reference has a null value.

For example this code:

 var script : Game3_Player = dead.GetComponent(Game3_Player);

would throw a NullReferenceException if the "dead" variable is set to "null". A reference variable is null if you never assign it a value or if it's set explicitely to null.

My suggestion would be that you use MonoDevelop to debug your code inside Respawn(), to see the values of the variables.

You read about using MonoDevelop with Unity here :http://docs.unity3d.com/Documentation/Manual/HOWTO-MonoDevelop.html

Comment

People who like this

0 Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image carter-carl30 · May 21, 2013 at 11:16 PM 0
Share

In the Game3_Player script dead is either true or false, am I right in understaning that "null" means no value/nothing set? if so surely true or false is a value? (forgive me if i'm getting this totally wrong, i'm still climbing the very steep learning curve!)

avatar image carter-carl30 · May 21, 2013 at 11:18 PM 0
Share

it's pointing specifically to this line of code when i double click the log: if(script.dead) {

avatar image ricardo_arango ♦♦ · May 21, 2013 at 11:26 PM 0
Share

"dead" is a boolean in the first script.

and "dead" is a reference to a GameObject in the second script.

Try renaming them to distinguish them more easily

avatar image carter-carl30 · May 21, 2013 at 11:38 PM 0
Share

var dead : GameObject = GameObject.FindWithTag("goal"); //more efficient than Find var dead : Game3_Player = dead.GetComponent(Game3_Player); //get script instance if(script.dead) {

what I was trying to do here (using script from answers) is access the dead var from the script on the character and if dead is true then do respawn.

to try and simplify what i'm trying to do (i'm getting in a right mess) is from my respawn script see if the player is dead from character controller script and if dead = true then respawn minus one life at my spawn point.

avatar image ricardo_arango ♦♦ · May 21, 2013 at 11:48 PM 0
Share

Why don't you assign the "dead: GameObject" variable directly when you create the Player? This is better than doing a Find.

You would define it outside of the Update function in the Respawn script and when you create the Player set the reference to it.

That would be better than checking for that object in every frame.

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

14 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Making a character jump with the Character Controller Component instead of Capsule Collider 0 Answers

flying should only be possible while fuel 0 < but it continues so long as space is held 2 Answers

How do I make a respawn system? 1 Answer

How to test if a charactor is walking on terrain (to make a walking noise) 1 Answer

Multi-Touch help 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges