Unity trigger not triggering - unity3d

I'm having one of the most basic issue but I really can't get it work on my project. I even tried to re-create a blank project and create a similar situation, in this new project, the trigger is working well but not in my old one and I can't figure out why so I'm looking for help here.
Here is some explanation on what I have, first, the character :
My character with :
Box Collider 2D with NOTHING check (so isTrigger, used by effector, etc, they are NOT checked)
Rigidbody 2D Dynamic, simulated, continuous and stat awake.
Then, the platform prefab :
Platform prefab (BoxCollider2D with Used By Effector, Platform Effector 2D)
Child of platform prefab > front part (just a sprite renderer)
Child of platform prefab > triggerPart (Empty object scale 4,1,1 with BoxCollider2D with is Trigger checked and the script "triggerBounce"
Here is the script triggerBounce : (For now, I'm just trying to see if the trigger is working)
private void OnTriggerEnter2D(Collider2D collision)
{Debug.Log("triger in " + name + " " + collision.name);}
private void OnTriggerStay2D(Collider2D collision)
{Debug.Log("triger stay " + name + " " + collision.name);}
private void OnTriggerExit2D(Collider2D collision)
{Debug.Log("triger exit " + name + " " + collision.name);}
I searched a lot of help on the internet before posting this, like this :
Putting all the element on the same Z position to be sure they're triggering
Reproducing the most simple situation, which I made work in an other project, but not in this one
I checked that in my project settings > physics 2D the Y gravity was -9.81
I tried resizing the boxCollider2D size
Verified the script triggerBounce was launched by debug.log("start") in his start
And even tough I did all this, it doesn't work any better.
Here is a pic of the situation, it can help you understand the problem :

Thanks to #Morion, I found what the problem was.
All my GameObject had the "default" layer and the collision matrix wasn't checked for 2 default.
So, I went to Edit > Project Settings > Physics 2D
and check the box where the row and column was default.

Related

unity collision doesnt work, what is the problem in my code?

im trying to track collsion on a unity project and i dont get whats wrong
thats the code i'm working with.
im trying to destroy an object on collision but it doesnt work for some reason.
void OnCollisionEnter(Collision col)
{
if (col.collider.gameObject.tag == "Enemy")
{
Destroy(col.gameObject);
Debug.Log("collided");
}
}
it hits the object but nothing happends i dont get a message and the object doesnt get destroyed
Assuming that the script you posted is a component of some kind of a character (which it should be since you are looking for an Enemy using its tag) and you have proper Rigidbody components with proper settings and Colliders, you should use:
void OnCollisionEnter(Collision col)
{
// You can also use col.gameObject.tag == "Enemy" since it does the same thing as CompareTag().
// Although using col.gameObject.tag == "Enemy" is less performant.
if (col.gameObject.CompareTag("Enemy"))
{
// Using print to get proper information on what is happening.
print("destroyed " + col.gameObject.name);
// Destroying the gameObject with the tag "Enemy"
Destroy(col.gameObject);
}
}
If you wanted to destroy the player object then you should change the tag accordingly and have this script as a component of the enemy.
The most common issues if nothing is showing up can be:
the object has no RigidBody (or RigidBody2D if you are in a 2D project) component
the 2 objects are in 2 layers which don't collide with others (or the same layer which don't collide with itself). Check both objects' layers, and go to Edit -> Project Settings -> Physics (or Physics2D if the project is in 2D) and go at the bottom and check that the layers collide with each other (the check box is on)
one of the 2 colliders is in 2D and the other in 3D

Why 'Is Kinematics' works different on HoloLens?

Overview
I wanted to have a cube, that I can drag around the scene with the components Collider, Rigidbody and ObjectManipulator. In play mode everything works fine, but running it on the hololens, the cube starts flying around after dragging it a few time.
Steps to reproduce (All components are set via editor, not via code)
Create new project and set it up for AR/HoloLens
Import MRTK 2.4
Create cube with a Box Collider. Set Is Trigger = true
Add Rigidbody to cube. Set Use Gravity = false and Is Kinematic = true
Add Object Manipulator to cube. I have a method getting called after On Manipulation Ended, but don't know if thats important.
Expected behavior
The rigidbody is set to Is Kinematic = true and Use Gravity = false, so that the cube stays still/stops moving after releasing dragging it. This works while trying it inside the unity play mode. But running it on the hololens, the cube behaves like Is Kinematic = false and starts flying around after interacting with it. Sometimes after the second drag and sometimes after the third time drag.
Error
Before updating this post, I didnt noticed the development console in left corner of my hololens. At the beginng of the scene I get the message [Physics.PhysX] BV4 midphase only supported on intel platforms but at that moment everything is fine. As the cube begins to fly around I get the a NullReferenceExeption: Object reference not set to an instance of an object.
I fixed my issue. I know the approximate cause, but I do not fully understand it. The method, getting called after OnManipulationEnded caused that.
I have a list, getting filled and drained by OnTriggerEnter/-Exit (exit looks the same, except add→remove):
private void OnTriggerEnter(Collider other){
if (other.gameObject.layer != 31) return;
_objectsCollidingWith.Add(other.gameObject);}
OnManipulationEnded triggered this method:
private int GetMeshes(List<KeyValuePair<Transform, Mesh>> transMeshes){
foreach (GameObject go in _objectsCollidingWith)
{
transMeshes.Add(new KeyValuePair<Transform, Mesh>(go.transform , go.GetComponent<MeshFilter>().mesh));
}
return transMeshes.Count;}
So I got alot of nullreferences from GetMeshes, because some gameobject in the list _objectsCollidingWith were null. Thats because the mesh is getting updated every once in a while. That caused a lot of nullreferences until the cube just flew away.
I used the whole time the logging provider via the device portal and couldnt see what is causing this errors. But after running the project via holographic emulation I could see in the console where they were coming from.
How did I fixed my problem?
I found this post because I realized that my OnTriggerExit didn't get called and cased having null objects and some spatial meshes with the same name triggered OnTriggerEnter very often. Also I added this line in the foreach loop in GetMeshes because once in a while there is still a null object:
if (go == null)
continue;
PS: Please forgive the strange code formatting, somehow the editor here on so does not allow me to place the brackets somewhere else

Unity is always throwing a Win32 Exception [duplicate]

so I'm new to Unity and I've been trying to test the scene with the script attatched to a character. However, it keeps saying "The associated script cannot be loaded. Please fix any compile errors and assign a valid script." It also says that the name of the file could be different from the name in the code but it isnt, and also it says that the code could be missing MonoBehaviour Scripts. It wont even allow me to attach the script to characters because it cant find the script class.
I've copied and downloaded character movement codes from the internet but they didnt work either. I've also tried deleting and re-making the CS files but that didnt work either. Even adding empty scripts to characters didnt work unless i do it from "Add component"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
SpriteRenderer sprite;
Rigidbody2D rigid;
// Start is called before the first frame update
void Start()
{
sprite = GetComponent<SpriteRenderer>();
rigid = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
if (Input.GetKey("d"))
rigid.velocity = new Vector2(2, 0);
else if (Input.GetKey("a"))
rigid.velocity = new Vector2(-2, 0);
}
}
There are also these errors in Unity if that helps
I think your class name is different from file name.
Unity apparently can't handle apostrophes (single-quote ') in the directory name of the editor. You need to get rid of the apostrophe in your directory name. Once you make that change, Unity should be able to build the scripts as intended.
Edit: This has been fixed in more recent versions - see https://issuetracker.unity3d.com/issues/scripts-do-not-get-compiled-if-the-unity-editor-path-contains-apostrophes for reference
First, it is recommended to use "Add component" to create a script, if you want to attach it to a GameObject, as it automatically imports necessary libraries. Implementing MonoBehaviour is necessary for adding a script to a GameObject.
Second, FixedUpdate() should not be set to private, it does not need an access modifier, just like Start(), see https://docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html.
Third, the errors in your first screenshot seem to imply that there is a problem with your Unity installation. Try reinstalling it and make sure that the Editor you install matches your operating system (64 or 32 bit?).
Fourth, the second screenshot is shown when you use any obsolete libraries or classes, which does not seem to be the case in the script you shared.
Hope that helps.
It's basically because you deleted some script or renamed it or degraded unity version. you might have to reassign the script at the required position/component.
Note: Make sure that class name is the same as the script name in unity.

How to stop NavMeshAgent separating from Animator?

I am working on a research project that uses a NavMeshAgent. I currently have a very simple scene where an agent is spawn at the start, walks through an "entrance" trigger collider, an "exit" trigger collider, then ultimately collides with a "destroyer" trigger collider with a script that ends the scene. Nothing complex, no physics collisions should be occurring.
I've been running some simulations both in the editor and in -batchmode -nographics via an executable that logs a basic runtime statistic when the scene ends. I found that in both the Unity editor and the CLI execution that occasionally the scene's execution time would spike. I finally caught what was happening in action- the NavMeshAgent component was becoming detached from my agent and floating out in front of it.
In this picture you can see the two colliders on the agent (one very small through his body for physics and one larger one for his "personal space",) the exit trigger collider (the giant red box on the right,) and floating between the two is a capsule-shaped NavMeshAgent component.
I used this unity page detailing how to use NavMeshAgents with animators, but after recreating their recommended setup, I am still having the issue.
Does anyone have any solutions for anchoring the NavMeshAgent to the agent itself?
I met exactly the same problem, where making the NavMeshAgent component a child and setting the NavMeshAgent's local position in every frame solved the problem.
private NavMeshAgent agent;
void Awake()
{
agent = gameObject.GetComponentInChildren<NavMeshAgent>();
anim = gameObject.GetComponent<Animator> ();
}
private void Update()
{
agent.transform.localPosition = Vector3.zero;
// todo:
// set animator
}
void OnAnimatorMove ()
{
// Update position to agent position
transform.position = agent.nextPosition;
}
For those of you who stumbled here, but for whom the accepted answer did not work. Make sure that navMeshAgent.updatePosition is set to true or that it is not changed within a script. This could be the cause of the separation.
NavMeshAgent navMeshAgent;
// This may cause the agent to separate
navMeshAgent.updatePosition = false;
// This will make sure it is synced
navMeshAgent.updatePosition = true;
This works as of version 2022.1 of the Unity API. Here are the docs for the function : https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent-updatePosition.html

Display Player Coordinates on Simple GUIText

Novice here - of course. I'm using Unity 5, and am looking to display on screen the coordinates of a player using a FPS camera. The main reason is I'm using a camera path animator to fly around a terrain scene I built for class, and think by logging coordinates via walking around in FP will make placing my camera path waypoints a lot easier.
What I have done:
-Created new empty game object -Added Component -> Rendering -> GUIText -Added Component -> New Script ->C#
Now I of course searched around to find a solution and found this:
function OnGUI () {
GUI.Label (Rect (10,120,500,100), "X = " + transform.position.x + " Y= " + transform.position.y + "Z= " + transform.position.z);
}
Which is great! But I am not a strong C# programmer by any means, but I do know this needs a Player variable of some sort yet. So please, could anyone simply direct me, or mind posting the code needed to make player coordinates appear on the screen. This doesn't have to be pretty or anything, I just need to write down the data as I walk around in FP. (unless you want brownie points and know of a way to log coordinates into a .txt file on button press... hahaha Thanks guys!
I'm not sure this is what you want....
Create new GameObject(GUIText) and make it's parent with your player game object. Now GUIText game object will follow your player object automatically
Add new script(i.e, PlayerPositionLogger.cs). to GUIText game object.
Find player script on void Start() on PlayerPositionLogger.cs or declare public Player player; and link player object on editor.
Update content of GUIText with player object.
gist.github.com/growingdever/39b758d5f3967c143744
Select the player object
Add component > New Script
Add the following code to the script (replace Start and Update)
void OnGUI() {
GUI.Box (Rect (10,10,100,90), "Player position: X:" + transform.position.x +
" Y: " + transform.position.y + " Z: " + transform.position.z);
}
When you enter playmode it should do what you want. Your main problem was GUI layout.