How to cite a specific object in code c# / reloading a scene
I am a new young programmer that is working on a game, and i ve faced this issue since a day and i cant find a solution for it. So I came here seeking for help.
I made a script for damaging both the player and the enemy at the same time:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Damageable : MonoBehaviour {
public float maxHealth;
private float health;
public Image healthBar;
void Start()
{
health = maxHealth;
}
void Update()
{
if (health > maxHealth)
{
health = maxHealth;
}
if (health <= 0)
{
Destroy(gameObject);
}
}
public void Damage ( int damageValue)
{
health -= damageValue;
healthBar.fillAmount = health / maxHealth;
Debug.Log(health);
}
}
It works properly, but i want the scene to reload on player death. i tried adding: Application.LoadedLevel (Application.loadedLevel); but now not only when the player dies the scene reloads, but also when the enemy is killed. I want to find a way to specify that only only when the player dies the scene reloads. It will be great if any of u pro coders will help me. :D
P.S. dont mind the damageValue thingies cuz they are in another script.
Answer by ShadyProductions · Aug 08, 2018 at 12:25 PM
Add a bool field
public bool IsPlayer;
then in the editor find the damageable script on the player and set the IsPlayer field to true and check for it when u destroy the gameobject.
if (health <= 0)
{
if (IsPlayer)
{
SceneManager.LoadScene(scenename);
}
else
{
Destroy(gameObject);
}
}
Thank you sir, but i have one last question: do i need to put at the top using UnityEngine.Scene$$anonymous$$anager; or no need?
never $$anonymous$$d my last comment, it tells me when i dont put using UnityEngine.Scene$$anonymous$$anager; that there is no such as Scene$$anonymous$$anager. and when i put it, it tells me UnityEngine doesnt contain Scene$$anonymous$$anager
And how do we do this exactly:"and set the IsPlayer field to true and check for it when u destroy the gameobject." Can you be more precise please. i Really appreciate your help
I assume your script is placed on every enemy and player object in the scene yes? So if you click on the player gameobject in the inspector you should see the 'IsPlayer' checkbox in the properties windows of that gameobject, you can enable it there. And then just put that piece of code that I shared into Update method. And Scene$$anonymous$$anager is based on your unity version, its for the newer versions, you are probably using an old version of unity so you have to use Application.LoadLevel
Your answer
Follow this Question
Related Questions
Should I reload scene after player dies or make custom system to handle that? 0 Answers
Enemies cannot kill Player. 0 Answers
how to load scenes so that my location is saved 0 Answers
References to Prefab get lost on start 1 Answer
Respawn fix 1 Answer