Hello,
i do Junior Programmer:Create with Code 2- Unity Learn ,
to avoid restarting the game each time, I created a script to restart the scene :
using UnityEngine;
using UnityEngine.SceneManagement;
public class restartLevel : MonoBehaviour
{ public string SceneName ;
Update()
{ if(Input.GetKeyDown(KeyCode.R))
{ SceneManager.LoadScene(SceneName);
}}}
Or :
using UnityEngine;
using UnityEngine.SceneManagement;
public class restartLevel : MonoBehaviour
{ Update()
{ if(Input.GetKeyDown(KeyCode.R))
{ SceneManager.LoadScene(0);
}}}
Or :
using UnityEngine;
using UnityEngine.SceneManagement;
public class restartLevel : MonoBehaviour
{ Update()
{ if(Input.GetKeyDown(KeyCode.R))
{ SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}}}
My problem :
The scene is playing, but my variables in my other scripts are going crazy, the player is jumping lower and lower with each replacement, my spawn objects are composing really weird.
Should I add a line of code? To reset my variables.
Is the script bad?
Here is the player controller code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController3 : MonoBehaviour
{ private Rigidbody playerRb;
private Animator playerAnim;
private AudioSource playerAudio;
public float forceJump;
public float gravityModifier;
public bool isOnGround = true;
public bool gameOver = false;
public ParticleSystem explosionParticle;
public ParticleSystem dirtParticle;
public AudioClip jumpSound;
public AudioClip crashSound;
void Start()
{ playerRb = GetComponent<Rigidbody>();
playerAnim = GetComponent<Animator>();
playerAudio = GetComponent<AudioSource>();
Physics.gravity *= gravityModifier;
}
void Update()
{ if (Input.GetKeyDown(KeyCode.Space)&& isOnGround && !gameOver )
{ playerRb.AddForce(Vector3.up * forceJump, ForceMode.Impulse);
isOnGround = false;
playerAnim.SetTrigger("Jump_trig");
dirtParticle.Stop();
playerAudio.PlayOneShot(jumpSound, 1.0f);
}}
private void OnCollisionEnter(Collision collision) {
if(collision.gameObject.CompareTag("Ground")&& !gameOver)
{ isOnGround = true;
dirtParticle.Play();}
else if(collision.gameObject.CompareTag("obstacle")&& !gameOver)
{ gameOver = true;
playerAnim.SetBool("Death_b", true);
playerAnim.SetInteger("DeathType_int", 1);
explosionParticle.Play();
dirtParticle.Stop();
playerAudio.PlayOneShot(crashSound, 1.0f);
}}}
unity 2021.3.2f1