How to destroy instantiated button upon collision exit - Unity 3D - unity3d

I am a beginner in Unity and I am currently making a simple game. I have a problem where the instantiated Button is not destroyed.
The process of the script is to instantiate a button and destroy it upon collision exit. But when I move out of the object, the object stays and it is not destroyed. i don't know if there is something wrong with the Destroy code of line.
Here is the script for the collision:
using UnityEngine;
using UnityEngine.UI;
public class InteractButtonPosition : MonoBehaviour
{
public Button UI;
private Button uiUse;
private Vector3 offset = new Vector3(0, 0.5f, 0);
// Start is called before the first frame update
void Start()
{
//uiUse = Instantiate(UI, FindObjectOfType<Canvas>().transform).GetComponent<Button>();
}
// Update is called once per frame
void Update()
{
//uiUse.transform.position = Camera.main.WorldToScreenPoint(this.transform.position + offset);
}
private void OnCollisionEnter(Collision collisionInfo)
{
if(collisionInfo.collider.name == "Player")
{
uiUse = Instantiate(UI, FindObjectOfType<Canvas>().transform).GetComponent<Button>();
uiUse.gameObject.SetActive(true);
uiUse.transform.position = Camera.main.WorldToScreenPoint(this.transform.position + offset);
}
}
private void OnCollisionExit(Collision collisionInfo)
{
if(collisionInfo.collider.name == "Player")
{
Destroy(uiUse);
}
}
}

The code does exactly what you have written, which is destroying uiUse which is a Button component. If you go and inspect your game object in the scene, you will see, that indeed, the button component has been destroyed.
What you want to do is to destroy the GameObject the button component is attached to, like: Destroy(uiUse.gameObject)

Related

Interacting with 3D object placed on Vuforia's ground plane using ray casting

Hello so I've been looking for a solution for my problem but looks like there is absolutely nothing about it.
I'm working on a scene where I have some 3D object renderred on a ground plane and my goal is making an animation on that 3D object start by tapping it. I'm using latest version of vuforia 10.4 with Unity 2020.3.9f1. I have a script for instantiating the 3d Model and making the plane finder disappear as long as it doesn't lose tracking.`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class sceneManager : MonoBehaviour
{
private string level = "snake";
public GameObject[] renderredPrefab;
public GameObject ground;
public GameObject groundFinder;
private int levelChecker(string levelName)
{
if (levelName == "snake")
return 0;
else return 1;
}
public void spawnObject(int i)
{
Instantiate(renderredPrefab[levelChecker(level)], new Vector3(0, 0, 0), Quaternion.identity, ground.transform);
}
public void groundFinderOff()
{
groundFinder.SetActive(false);
}
public void groundFinderOn()
{
groundFinder.SetActive(true);
}
}
And another one to trigger the animation following the game object's tag hereusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class animationTriggerManager : MonoBehaviour
{
private Animator m_Animator;
private string objectName;
private GameObject[] eos;
private GameObject snake;
[SerializeField]
private Camera ARCamera;
// Start is called before the first frame update
void Start()
{
// Get the different eos present on the scene
for (int i = 0; i < eos.Length; i++)
{
eos[i] = GameObject.FindWithTag("myEolienne" + i);
}
// Get snake game objecct in the scene
snake = GameObject.FindWithTag("Snake");
}
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began)
{
Ray ray = ARCamera.ScreenPointToRay(Input.GetTouch(0).position);
if (Physics.Raycast(ray, out RaycastHit hit))
{
objectName = hit.collider.name;
Debug.Log("raycast touched " + hit.transform.name);
switch (objectName) //Get the Animator depending on which gameObject been tapped on.
{
case "myEolienne1":
m_Animator = eos[0].GetComponent<Animator>();
// Launch the animation on the gameObject that's been tapped
m_Animator.SetTrigger("Helice_Rotate");
Debug.Log("rotate launched");
break;
case "myEolienne2":
m_Animator = eos[1].GetComponent<Animator>();
// Launch the animation on the gameObject that's been tapped
m_Animator.SetTrigger("Helice_Rotate");
Debug.Log("rotate launched");
break;
case "myEolienne3":
m_Animator = eos[2].GetComponent<Animator>();
// Launch the animation on the gameObject that's been tapped
m_Animator.SetTrigger("Helice_Rotate");
Debug.Log("rotate launched");
break;
case "Snake":
m_Animator = snake.GetComponent<Animator>();
m_Animator.SetTrigger("snakeMoving");
break;
}
}
}
}
}
`
Note that each 3D model has different parts grouped in one parent that has a mesh collider on the parent only.enter image description here
The rendering works perfectly but I can't figure out what's wrong with my raycasting script. Note that I first tried with 3D model on image target and it worked fine.
Thanks in advance !

Destroy GameObject when its clicked on

I'm making a building mechanic in my game and I want to be able to clear out certain objects around the map (trees, other decor) so I have room to build. I've tried using a ray cast to find what object is being clicked on and destroy it but that doesn't work.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectDestroy : MonoBehaviour {
// Start is called before the first frame update
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
Debug.Log (Input.mousePosition);
if (Physics.Raycast (ray, out hit)) {
if (hit.collider.gameObject == gameObject) Destroy (gameObject);
}
}
}
}
Here is a little example script:
public class Destroyable : MonoBehaviour
{
private void OnMouseDown()
{
Destroy(gameObject);
}
}
You can attach this script to the GameObject you want to destroy and then during Play-Mode you can click on it to destroy it. It is modifiable if you just need it in your In-Game-Editor.
Note: You need an active Collider on the same Gameobject.
Edit:
The following script shows an example for changing the color of the object:
public class Destroyable : MonoBehaviour
{
public Color mouseHoverColor = Color.green;
private Color previousColor;
private MeshRenderer meshRenderer;
private void Start()
{
meshRenderer = GetComponent<MeshRenderer>();
previousColor = meshRenderer.material.color;
}
private void OnMouseDown()
{
Destroy(gameObject);
}
private void OnMouseOver()
{
meshRenderer.material.color = mouseHoverColor;
}
private void OnMouseExit()
{
meshRenderer.material.color = previousColor;
}
}
You don't need to add this script on every object, just add it to a manager and also I think you are missing Raycast parameters.
To see where you ray is going you can use Debug.Ray()
Also, I would prefer you use #MSauer way since is much cleaner for what you want, just be sure the object contains a collider, I think they can be a trigger and the click will still happen.

Control object rotation by mouse click in unity

I need help with my project in unity
I want to stop each object by clicking on it.
What I did so far:
all my objects rotate but when I click anywhere they all stop, I need them to stop only if I click on each one.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EarthScript : MonoBehaviour
{
public bool rotateObject = true;
public GameObject MyCenter;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if(rotateObject == true)
{
rotateObject = false;
}
else
{
rotateObject = true;
}
}
if(rotateObject == true)
{
Vector3 axisofRotation = new Vector3(0,1,0);
transform.RotateAround(MyCenter.transform.position,axisofRotation, 30*Time.deltaTime);
transform.Rotate(0,Time.deltaTime*30,0,Space.Self);
}
}
}
Theres two good ways to achieve this. Both ways require you to have a collider attatched to your object.
One is to raycast from the camera, through the cursor, into the scene, to check which object is currently under the cursor.
The second way is using unity's EventSystem. You will need to attach a PhysicsRaycaster on your camera, but then you get callbacks from the event system which simplifies detection (it is handled by Unity so there is less to write)
using UnityEngine;
using UnityEngine.EventSystems;
public class myClass: MonoBehaviour, IPointerClickHandler
{
public GameObject MyCenter;
public void OnPointerClick (PointerEventData e)
{
rotateObject=!rotateObject;
}
void Update()
{
if(rotateObject == true)
{
Vector3 axisofRotation = new Vector3(0,1,0);
transform.RotateAround(MyCenter.transform.position,axisofRotation, 30*Time.deltaTime);
transform.Rotate(0,Time.deltaTime*30,0,Space.Self);
}
}

Unity AnimationEvent has no reciever

Here are the two Error messages I am receiving.
This seems to only happen when the Run animation is playing. Any help would be appreciated.
I am building this game for android and I am using mouse clicks to move the character. Since mouse clicks translate to touch events this should have no barring on the game as far as I know.
I guess I should also note that the animations play fine while playing the game.
'defaultModelfbx' AnimationEvent 'FootL' has no receiver! Are you missing a component?
'defaultModelfbx' AnimationEvent 'FootR' has no receiver! Are you missing a component?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerController : MonoBehaviour
{
float speed = 10;
float rotSpeed = 5;
Vector3 targetPosition;
Vector3 lookAtTarget;
Quaternion playerRot;
bool moving = false;
Animator thisAnim;
void Update()
{
thisAnim = GetComponent<Animator>();
// Get movement of the finger since last frame
if (Input.GetMouseButton(0))
{
SetTargetPosition();
}
if (moving)
{
Move();
}
}
void SetTargetPosition()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 1000))
{
targetPosition = hit.point;
lookAtTarget = new Vector3(targetPosition.x - `transform.position.x, 0, targetPosition.z - transform.position.z);`
playerRot = Quaternion.LookRotation(lookAtTarget);
moving = true;
}
}
void Move()
{
thisAnim.SetFloat("speed", 1);
transform.rotation = Quaternion.Slerp(transform.rotation, playerRot, rotSpeed * Time.deltaTime);
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
if (transform.position == targetPosition)
{
moving = false;
thisAnim.SetFloat("speed", 0);
}
}
}
I had the same error, but with a different cause and solution.
All my code was in a (grand)parent gameobject (e.g. WerewolfPlayer) and I wanted to keep it this way. The animator was in a (grand)child gameobject (e.g. WEREWOLF_PBR) and it couldn't find the animation events:
To fix this, I bubbled-up the event from the child gameobject to the parent:
I edited the PlayerController.cs in the parent gameobject (e.g. WerewolfPlayer) to find the new "hand off animation events" script and fire the animation events when they happen:
using UnityEngine;
using System;
public class PlayerController : MonoBehaviour
{
private HandOffAnimationEvent handOffAnimationEvent;
// called when animation event fires
public void Pickup()
{
Debug.Log("player picks up object here...");
}
void OnEnable()
{
handOffAnimationEvent = GetComponentInChildren<HandOffAnimationEvent>();
handOffAnimationEvent.OnPickup += Pickup;
}
void OnDisable()
{
handOffAnimationEvent.OnPickup -= Pickup;
}
}
The new HandOffAnimationEvents.cs was added to the child gameobject (e.g. WEREWOLF_PBR) and when the animation event fires, it fires its own event:
using UnityEngine;
using System;
public class HandOffAnimationEvent : MonoBehaviour
{
public event Action OnPickup;
// This is the animation event, defined/called by animation
public void Pickup()
{
OnPickup?.Invoke();
}
}
Okay thanks to Nathalia Soragge I have found the solution to the problem.
If you look closely at the animation window you can see two white dashes at the top of the time line. I have clicked on one of them in the picture, and sure enough it is one of the events that were throwing the error message.
I am assuming I can just delete these two events since I do not have them anywhere in code. In this case it is looking for the events in my PlayerController since it is attached to my Model defaultModelfbx
UPDATE: I have deleted both events and now everything is running smoothly. Thanks again Nathalia!!!!!!! ;)
If you don't want to listen to any events, you can set Animator.fireEvents to false.
public Animator animator;
void Start()
{
animator.fireEvents = false;
}
https://docs.unity3d.com/ScriptReference/Animator-fireEvents.html
I had the same problem.I solved this by deleting all animation events and recreating all of them again.

Unity child object sometimes jumps to vector3(0,0,0)

I have a very annoying bug, and I can't get rid of it.
The situation is, that I have a parent with the following script attached, and a trigger box2d collider. It has a child, with a rigidbody2d(kinematic, gravity=0, freeze position x, and rotation z), a sprite renderer and a polygon collider (with 4 edges).
My problem is, when the scene is loaded, sometimes my child objects (always random how much of them and which ones), jumps to transform.position 0,0,0.
I link the script, that is attached to the parent
using UnityEngine;
using System.Collections;
public class FallingSpikeHazard : MonoBehaviour
{
public GameObject spike;
private Rigidbody2D spikeRigidbody;
[SerializeField]
private Vector3 startPosition;
void Awake ()
{
startPosition = spike.transform.localPosition;
}
void Start ()
{
spikeRigidbody = spike.GetComponent<Rigidbody2D> ();
Helper.JustReset += ResetMe;
Invoke ("CheckPosition", Time.deltaTime);
}
void CheckPosition ()
{
if (spike.transform.localPosition != startPosition) {
Debug.LogError ("t1" + spike.transform.localPosition);
spike.transform.localPosition = startPosition;
Debug.LogError ("t2" + spike.transform.localPosition);
}
}
void OnDestroy ()
{
Helper.JustReset -= ResetMe;
}
void ResetMe ()
{
spikeRigidbody.gravityScale = 0;
spikeRigidbody.isKinematic = true;
if (startPosition != Vector3.zero) {
spike.transform.localPosition = startPosition;
}
}
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag.Equals ("Player")) {
spikeRigidbody.isKinematic = false;
spikeRigidbody.gravityScale = 1;
}
}
}
Events are not called, in other hand, if I disable the script, it keeps happening. Nothing have reference to these GameObjects. I don't have animations, or animator attached.
What could cause my problem?
You need to have a Rigidbody2D component in the parent GameObject in order for the OnTriggerEnter function to be called.