Load Scene when Enemy Collides with Player-Unity - c#

Unity 2D. I am trying to load EndGameScene when an enemy collides with my player, but I can't seem to get it to work.
My tags are "Player" and "enemy".
This is the current code.
Code:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class EndGame : MonoBehaviour
{
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == "enemy")
{
SceneManager.LoadScene("EndGameScene");
}
}
}

I'm new to Unity (and it's been some time since last time I used it), so this check list may be incomplete, but still worth a try:
Put a Debug.Log("it collides!") at the beggining of your OnCollisionEnter function, so you can be sure that it is actually detecting a collition.
If it doesn't print anything:
Check if you are ussing a collider in both the player and the enemies.
The player's collider should have the "Is trigger" checkbox selected, so it triggers a OncollitionEnter event.
If it prints the message:
Check if there is an error message under the printer message, may be that it can't find the scene.
Be sure that you typed correctly the name/tag of the enemies (I suppose the script is on your player)

there's a better way to make the collision:
change the name here if (collision.gameObject.name == "enemy")
and make it like this if (collision.gameObject.tag == "Enemy")
and go to the enemys in you scene and add the Enemy tag to them

It might be because you have not built the scene into the project's build settings (in the unity interface):
Go to the Game Over scene/ open it by going to File>OpenScene>Scenes(folder)>Game Over (scene name)
click 'File' (top left corner)
click 'Build Settings' option
click 'Add Open Scenes button'
make sure the scene you want to add is listed and checked
click 'Build' (on bottom right)

Related

Making a reset menu for my game in unity but don't know how on collision set to a different scene

So I've just been tinkering with unity and all yesterday I was making a little game. I have a main menu when you start the game, the game itself and a gameover menu when you die that puts you back at the home screen, but I have no clue how to set it when a thing/enemy hits the player, It brings you to the restart menu on collision with it. anyone know any code to help out, I've been trying to find videos but they are not what I need. I need when on collision set scene to GAMEOVER. But don't know how, PLZ help.
So to what I understand you want to make a collision and restart you scene or go to another scene ?
You need to use something like this.
I added 3 possibiities of Scenemanager.LoadScene however you need to use them.
make sure to add the the using UnityEngine.SceneManagement; at the top
using UnityEngine.SceneManagement;
void OnCollisionEnter(Collision collision)
{
//if you want to load another scene
SceneManager.LoadScene("OtherSceneName");
//if you want to load the same scene you are on
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
//if you want to load the same scene you are on
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
To know if an object with a Collider was hit in Unity (e.g. the player) you need to add one of the OnCollision functions to your script:
OnCollisionEnter - is called when the object is first hit
OnCollisionStay - is called every frame while the object is being touched
OnCollisionExit - is called on the frame the object stops being touched
Then, in the function you can load a different scene using SceneManager.LoadScene

How to end a game in C# from a Collision

This is the current script that I have. I have a ball that is player, and I want a collision with my game object tagged as "pit" to end the game. When the game ends I want my game over canvas to pop up. The current script detects the hit when the player rolls over the pit, however, currently, nothing else happens. Both my player and pit have rigidbodies and colliders attached to them. I would really appreciate any help with how to get my code to work properly.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Trigger : MonoBehaviour
{
public GameObject GameManager;
private void OnTriggerEnter(Collider other)
{
Debug.Log("hit detected")
if(other.gameObject.tag == "pit")
{
GameManager.GetComponent<Game_Manager>().EndGame();
}
}
}
My EndGame code is in my GameManager script. The is the part of that script that deals with ending the game.
public void EndGame ()
{
player.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePosition;
hasGameStarted = true;
inMenuUI.gameObject.SetActive(false);
inGameUI.gameObject.SetActive(false);
gameOverUI.gameObject.SetActive(true);
}
If I'm correct in interpreting your question, your script successfully detects player death already. If you want a game over screen you have a couple of options:
You can create a UI canvas with a panel on it that obscures the whole screen and put the words Game Over.
Or, probably the better option is to create an entirely new Unity scene and make the Game Over canvas there. When you want to trigger the game over screen you simply use:
Scene manager.LoadScene("Scene name");
You have to add "using UnityEngine.SceneManagement;" at the top of your script. Also note you have to add your Game Over scene to the list of scenes in you game. I believe this can be done by navigating to File>Build settings>scenes and then pressing add open scenes assuming the game over scene is open.

How to log game objects colliding in Unity

This is my first unity project so I am fairly unfamiliar with everything the platform has. I am trying to log a message to the console when I have a my player game object run into a finish line. Both objects have Box Colliders on them and I have attached a C# script to the player object. Below is the code I have currently.
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Finish")
{
Debug.Log("Finish");
}
}
The problem is that when I move the player into the "Finish" object no logging appears inside the console.
Thanks in Advance!
This is the main player inspector tab
This is the finish line inspector tab
Your script attached to the player checks for a collision with an object with the tag "Finish". Your Object "Finish Line" has tag "untagged". You have to add a tag "Finish" to it to see it working.
With the updated question and screenshots, the problem is that you're checking for the "Finish" tag but the "Finish" GameObject's tag is set to "Untagged" so the if (col.gameObject.tag == "Finish") statement will not evaluate to true.
You have two options:
1. Select the "Finish" GameObject, click the tag that says "Untagged" and create new tag named "Finish". If you already have this tag, change the tag of the "Finish" GameObject from "Untagged" to "Finish" and your if (col.gameObject.tag == "Finish") code should work.
2. If you did not intend to use tag then just compare the GameObject by name instead of tag by simply replacing if (col.gameObject.tag == "Finish") with if (col.gameObject.name == "Finish").
If none of the two options above worked for you then OnCollisionEnter2D is not being called at-all. Put a Debug.Log outside the if statement like below and leave a comment about if there is a log or not.
void OnCollisionEnter2D(Collision2D col)
{
Debug.Log("Finish: " + col.gameObject.name);
}
Just first idea that came in mind:
- Did you add colliders on both of objects that should collide?
Without them engine will not generate events of colliding at all.

Trying to load a new scene when I enter a cube in Unity

So i have this code to enter a new scene:
using System.Collections;
using UnityEngine;
// add this line to use the SceneManagment library
using UnityEngine.SceneManagement;
public class LoadScenes : MonoBehaviour {
[SerializeField] private string loadLevel;
void onTriggerEnter(Collider other) {
if (other.CompareTag ("Player")) {
SceneManager.LoadScene (loadLevel);
}
}
}
I then add this script to the cube and select it a trigger. I then type in the scene that I want it to send me too, but when i walk into it nothing happens at all. I have tried different variations but it just doesnt seem to work.
My character that I am using is a unity asset called man in suit but I have selected its tag as "Player". Any suggestions would be great!
The Handler for your trigger won't be invoked
As Sunimal allready noted you need to fix the typo.
void OnTriggerEnter(Collider other) {
if (other.CompareTag ("Player")) {
SceneManager.LoadScene (loadLevel);
}
}
Ensure your Scene is included and checked in the Build Settings
As you can see in the Screenshot below i have added a SampleScene to my build settings. There are 2 ways of adding scenes into the build
By clicking "Add Open Scenes" you can add the scene which is
currently open to that list.
Drag & Drop the scene from your ProjectView into the List
Ensure your SceneName is set correctly
Your loadLevel field would in my case need to have the value "Scenes/SampleScene".
[SerializeField] private string loadLevel;
The player needs a collider
As you use the OnTriggerEnter method, your Player object needs to have some sort of Collider attached to it. This can be a BoxCollider, SphereCollider or some other Collider. Note that the "Is Trigger" checkbox needs to be checked. Else it won't act as trigger.
Edit: Thanks Eddge for correcting me. See this answer for a deeper explanation about Triggers.
Programatically ensure you have a BoxCollider component beside your LoadScenes component
You can add the RequireComponent Attribute at your class. It basically ensures you have the given type added as a component. This will also automatically add a box collider to an object, when you add this script.
[RequireComponent(typeof(BoxCollider))]
public class LoadScenes : MonoBehaviour {
/// your other code is here
}
Thanks to Sunimal for this hint!
What if that did not solve the problem?
If all this does not help, please provide an screenshot of the inspector of your Playerobject. That way we can see what components are attached to that object and how they are "configured"
SceneManagement
To use the SceneManager to load a scene you must ensure that your scene is in the build settings, per Tobias's answer.
Triggers
In all software development case does matter and it is incredibly important. OnTriggerEnter is not the same as onTriggerEnter, also note OnTriggerEnter(Collider col) is not the same as OnTriggerEnter(Collision col)
In order to use any of the trigger methods there are 3 things that are a must:
Both Objects have to have colliders.
One of the colliders have to be marked as a trigger.
One of the objects have to have a rigidbody.
The trigger event is sent to the object with the rigidbody and whatever object is the trigger, in the circumstance that both objects are triggers both will receive it.

On-collision script not working?

in advanced I would like to say if this is a really simple question with a simple answer, I apologize as I have just now gotten into programming.Basically, I'm trying to create a script that a block named blue(picture below) on collision with the FPSController, will get destroyed, here is my script:
using UnityEngine;
using System.Collections;
public class Cube : MonoBehaviour {
void OnCollisionEnter (Collision col) {
if(col.gameObject.name == "Blue") {
Destroy(col.gameObject);
print ("collison detected");
}
}
}
for some reason, though, whenever the fps controller collides with the object known as "Blue" nothing happens, the print() function is not triggered nor is the destroy() function
Thank you in advaned ;)
Rigidbody` is missing from your Cubes.
1.Attach Rigidbody component to both cubes.
2.Also,set both Cubes Rigidbody to Is-kinematic. You must set both Cubes Rigidbody to Is-kinematic so that the Character Controller wont be able to move it. Note that if your cube is falling down after adding Rigidbody, simply disable Use Graivty on the Rigidbody.
Important:
3.Delete FPSController. Since you will be interacting with other Rigidbody GameObjects, use RigidBodyFPSController. It can be found in Assets\Standard Assets\Characters\FirstPersonCharacter\Prefabs. Drag RigidBodyFPSController to the Scene then attach Cube script to it.
You will notice there is a Rigidbody attached to RigidBodyFPSController. Don't modify the settings of it.
That's it. Everything should be working as expected.
Cube settings:
RigidBodyFPSController Settings:

Categories

Resources