I'm fairly new to Unity and I've decided to work on a simple 2d platformer from youtube tutorials.
Everything works fine until I start using collisions. My problem isn't only that it doesn't work, It's that it doesn't appear at all on auto-complete.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class finishLine : MonoBehaviour
{
void Start()
{
}
void Update()
{
}
private void OnCollisionEnter2D(Collision2D col) {
if (col.gameObject.CompareTag("Player")) {
SceneManager.LoadScene("level2");
}
}
}
I've also added rigid bodies and box colliders to both objects (player and finish line).
Anyone know what's wrong?
Make sure that you used BoxCollider2D and not the 3D one.
If the autocomplete doesn't work try restarting VisualStudio or whatever IDE you use. If that doesn't work look in the Unity Settings under External Tools and try regenerating project files. That works for me sometimes.
So a couple things you might want to look into to fix this are:
Check if you have the right colliders on both your gameobjects (in this exmaple box collider 2D I assume)
Check if either of your colliders has the "Is Trigger" box check or not. If yes then uncheck it
Make sure your player gameobject has the "Player" tag and the same as the tag you compare in your script because compare tag is case sentitive
Check if you have your finishLine script on the object you want as the root object meaning it's the parent of all the other one inside it and has no parent (this doesn't need to be the case all the time but in this scenario it might help fix the problem)
Did you check the trigger box in the colliders?
Does any one of those objects have a rigid body?
Did you have other functions that destroyed the character when it reaches the destination that is meant to be the trigger?
You can try to set up a two new cubes for testing purposes to narrow down the problem.
Related
I created a project using the FPS Microgame in Unity Hub to learn scripting. I'm trying to play a simple particle effect when the player collides with it (in the future I'd love to be able to trigger it from farther away, maybe when crossing into a plane, but I'll learn that later). I created the following script and attached it as a component to the particle effect on the scene:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class portalTrigger : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
ParticleSystem ps = GetComponent<ParticleSystem>();
ps.Play();
}
}
And here's what the particle effect looks like in the Unity Inspector:
The particle effect plays when the game starts if I select Play on Wake so I disabled it because I want it to play when the user collides with it. Any ideas?
Thanks!
First I would add a debug print to verify that a collision is triggered in the onTriggerEnter method.
If that is not the case, I would check that both game objects have a rigid body and a collider. One (and only one) of the two colliders must have the isTrigger flag set.
Here is unity doc link for reference:
https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
Had you quite made sure that the isTrigger option in object main object has been checked true?
If not then either see the way to check it( What do I mean here is that if you only check isTrigger without making another collision than object won't stop even after the collision. It had been really hectic for me when I started.)
or use the OnCollisionEnter. If none of these happened then try printing to see if they're even colliding or not. C'mon you are trying to become a Unity scripter so best way is to debug anything you doubt about.
I'm trying to make a list where I can add objects in my scene, later on I'm going to loop through them to determine the closest object to my character and make the character perform certain actions. As soon as I created a list, it won't allow me to add any object to my list or reference it and I don't understand why that's happening. Here's a video to further clarify my issue
List Not working for me
my code for further inquiries
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RobberMechanic : MonoBehaviour
{
public List<GameObject> testing = new List<GameObject>();
// void Start()
// {
// }
// // Update is called once per frame
// void Update()
// {
// }
}
Note: wanted to clarify that my unity version was on 2020.3.1f and now I've tried upgrading to 2020.3.10f and this issue occurs in both versions
what you are trying to do is not possible as you are dragging a gameobject inside your list from the hierarchy onto a prefab in the assets folder. Dragging and dropping works on gameObjects that are already inside the a scene/hierarchy.
To achieve your goal you must either:
Add your Terrorist prefab in the scene. Drag your Sphinx object inside it. The Terrorist prefab will then have the appropriate reference of the gameObject and can be used properly.
Turn your Terrorist object into a scriptable gameObject you can then add all sorts of different properties and will be easier to manage. There are tons of videos and documentation on it as well.
You're trying to add a GameObject from your scene to a list in a Prefab which is not possible, you'll have to drop your prefab into the scene before adding game objects to it or make a Prefab of the object you're trying to add to the list.
I'm trying to create a script in Unity wherein the gravity will go to zero when the game starts. The problem is, the gravity was still there after I launched the game.
This is for a Unity3D game. I've already tried to change the variable name, add using System; and moved my script to the top of the Rigidbody component, but none of these things worked.
public class PlayerGrav : MonoBehaviour
{
public Rigidbody rb;
void Start()
{
rb.useGravity = false;
}
void Update()
{
}
}
I expected the gravity to be removed when the game launches, but in the actual output the gravity still remained, and the cube still fell downwards.
create a new scene
create a new cube
add rb = this.GetComponent<Rigidbody>() to your start function in your PlayerGrav script
attach your PlayerGrav script to the new cube
Hit play, and take look at the "use gravity" property from your new cube's inspector window (make sure the inspector isn't locked to other game object)
If the above tryout succeeds, then you need to check the other code/objects in your original scene. If there are massive other objects in your original scene, then I will suggest disable other objects first, and re-enable them back group by group to see which object/monobhevaiour is causing the issue.
I know this is an old question but I looked forever trying to find an answer to this. I am new to unity so it took me a long time to figure this out but I am using a Rigidbody 2d so this is what worked for me
gameObject.GetComponent<Rigidbody2D>().gravityScale = 0;
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.
I am trying to create an AR app using Unity & Vuforia. I have a 3D model that needs to be spawned when ground plane is detected.But this needs to happen only once.
The way Vuforia work is, it keeps on spawning objects when new plane is detected. So what i need to do is either detect plane only once or spawn the object only once. As i am new to Unity, i need help doing this. Great if someone could tell me what i need to do to achieve this.
Vuforia has updated.Now There is no DeploymentStageOnce script.Inorder to stop duplicating while we touch, we have to turn off Duplicate Stage in Content Positioning Behaviour (Script)Check the Inspector when we click Plane Finder.
In your app you should have a Plane Finder object somewhere with the following properties set by default
The Plane Finder object has a Behaviour component attached that calls a Position Content method if a plane was found. That method belongs to the Content Positioning Behaviour and it makes an instance (Clone) of your Ground Plane Stage. In order to avoid more than one instance you should import the vuforia Deploy Stage Once script located here: https://library.vuforia.com/articles/Solution/ground-plane-guide.html and you should change the Plane Finder Behaviour as the following:
I struggled a long with it, in short we must disable AnchorInputListenerBehaviour after hit.
I attached a new script on PlaneFinder with this code below:
<!-- language-all: c# -->
public void OnInteractiveHitTest(HitTestResult result)
{
var listenerBehaviour = GetComponent<AnchorInputListenerBehaviour>();
if (listenerBehaviour != null)
{
listenerBehaviour.enabled = false;
}
}
I added event on Plane Finder Behavior
That's all, I hope it will be useful.
For Updated Versions:
go to "Advanced" setting and "On Interactive Hit Test" script -> Select "Off" option for the script.
Most of the answers are correct but kind of obsolete, the correct way to do that is by code.
Create for example a gameObject called GameManager and pass the GroundPlaneStage and a prefab of the object you want to spawn to a script attached to that GameManager for example call it GameManagerScript.cs, and create a small function called spawnObjects which does the following:
public class SceneManagerScript : MonoBehaviour {
public GameObject objPrefab;
public GameObject ground;
private int count = 0;
public void spawnObject() {
Instantiate(objPrefab, new Vector3(count, 0, 0), Quaternion.identity, ground.transform);
count += 2;
}
}
then after that go to the PlaneFinder specifically to the PlaneFinderBehaviour.cs component you will have callbacks for OnInteractiveHitTest and OnAutomaticHitTest, in your case you need the OnAutomativeHitTest, click + and add a new callback (the function spawnObject in code above like in the image below)
also when you instantiate the object of your preference via the prefab don't forget to write the proper position updates to prevent the objects from getting added in the same position
also don't forget to make the GroundPlaneStage the parent of the object and realize that the position you are adding in the Instantiate() function is relative to that parent (GroundPlaneStage which is represented in the code above with the variable ground)
Finally don't forget to uncheck Duplicate Stage from the "Content Positioning Behaviour" component in the Plane Finder as shown in the picture below:
I hope that helps
please try the vuforia website for this problem
Introduction to Ground Plane in Unity