I wanna disable a canvas and destroy the object when the player leaves the collider - unity3d

I'm trying to make a animated UI and I wanna destroy the object after the player left the Collider and I don't really seem to find a way to do that.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.InputSystem;
public class Crate : MonoBehaviour
{
public float duration;
public GameObject animateObject;
public GameObject crateBox;
public Text crateText;
public GameObject crateImage;
public GameObject crate;
public bool playerInRange;
private bool crateOpened = false;
// Update is called once per frame
void Update()
{
if (crateOpened == false)
{
if (Keyboard.current.eKey.wasPressedThisFrame && playerInRange)
{
if (crateBox.activeInHierarchy)
{
crateBox.SetActive(false);
}
else
{
crateBox.SetActive(true);
crateOpened = true;
Animate();
}
}
if (crateOpened == true)
{
Destroy(animateObject);
}
}
}
private void OnTriggerEnter2D(Collider2D other) {
if(other.CompareTag("Player")) {
playerInRange = true;
crateImage.SetActive(true);
}
}
private void OnTriggerExit2D(Collider2D other) {
if(other.CompareTag("Player")) {
playerInRange = false;
crateBox.SetActive(false);
crateImage.SetActive(false);
}
}
private void Animate()
{
LeanTween.scale(animateObject, new Vector3(1f, 1f, 1f), duration);
}
}
I'm trying to make a animated UI and I wanna destroy the object after the player left the Collider and I don't really seem to find a way to do that.

I think the following is in the wrong place:
if (crateOpened == true)
{
Destroy(animateObject);
}
Try moving this inside the if statement in OnTriggerExit2D. What you are doing now is destroying your animateObject before it is animated. What I think you want is for animateObject to be destroyed when the player leaves the collider.

Related

Change Bullets as power

I am doing a 2d game and I want my player to be able to change bullets when he collides with an object(power) and destroy that object. I have a script and I was thinking that I need to implement 2 variables prefab ON/Off but now thinking much more I want to change with the help of a tag ( My player has in his script a public Rigidbody2D bullet) and this function
void Fire()
{
if (photonView.IsMine)
{
var firedBullet = Instantiate(bullet, barrel.position, barrel.rotation);
firedBullet.AddForce(barrel.up * bulletSpeed);
}
}
this is the script that I was working on for switching bullets but I think it will not work to change a bullet that I add in the inspector for the Character script , to disable from this script and add other bullet . How I can make it by tag?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponSwitching : MonoBehaviour
{
[SerializeField] private GameObject pickupEffect;
public GameObject[] DisablePrefab;
public GameObject[] EnablePrefab;
public int selectBullet = 0;
// Start is called before the first frame update
// Update is called once per frame
public void Bullet(Character bullet)
{
var effect = Instantiate(pickupEffect, transform.position, transform.rotation);
foreach (GameObject disable in DisablePrefab)
{
disable.SetActive(false);
}
foreach (GameObject enable in EnablePrefab)
{
enable.SetActive(true);
}
Destroy(gameObject);
Destroy(effect, 3.0f);
}
}
and I try this think with a BulletSwitch script to call the function from Weapon Switching script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletSwitch : MonoBehaviour
{
[SerializeField] private Character bullet;
// Start is called before the first frame update
private void Awake()
{
if (!bullet) bullet = GetComponent<Character>();
}
private void OnTriggerEnter2D(Collider2D other)
{
// or whatever tag your powerups have
if (!other.CompareTag("Bullet"))
{
Debug.LogWarning($"Registered a collision but with wrong tag: {other.tag}", this);
return;
}
var Bullet = other.GetComponent<WeaponSwitching>();
if (!Bullet)
{
Debug.LogError($"Object {other.name} is tagged PowerUp but has no PowerUp component attached", this);
return;
}
Debug.Log("Found powerup, pick it up!", this);
Bullet.Bullet(bullet);
}
}
inspector character
after my player collides with an object the bullets disappear.
You could make an array of prefabs and change to the correct bullet type when you hit a powerup by setting a CurrentBulletType variable to one of the types from the array. So when you hit powerup X, change bullet type to one of the types from the array.
public GameObject currentPrefab;
public GameObject[] bulletPrefabs;
private void OnTriggerEnter2D(Collider2D other)
{
string tagString = other.tag;
bool foundObject = true;
switch (tagString)
{
case "standard bullet":
currentPrefab = bulletPrefabs[0];
break;
case "fancy bullet":
currentPrefab = bulletPrefabs[1];
break;
case "even fancier bullet":
currentPrefab = bulletPrefabs[2];
break;
default:
foundObject = false;
break;
}
if (foundObject) other.gameObject.SetActive(false);
}
You can instead use a dictionary to directly reference the correct prefab by string name (tag) to make it easy to add more bullet types.
//dictionairy to reference bullet types quickly
public Dictionary<string, BulletTypes> bulletLibrary = new Dictionary<string, BulletTypes>();
//set these in the inspector
public BulletTypes[] bulletTypes;
[System.Serializable]
public struct BulletTypes
{
public string bulletName;
public GameObject prefab;
//public int bulletPower; //more data if you wish
}
private void Start()
{
//fill the dictionary based on the filled bullet type array in inspector
for (int i = 0; i < bulletTypes.Length; i++)
{
if (bulletTypes[i].bulletName != "")
bulletLibrary.Add(bulletTypes[i].bulletName, bulletTypes[i]);
else
print("bullet added, but name empty");
}
}
private void OnTriggerEnter2D(Collider2D other)
{
string tagString = other.tag;
//if the collided tag is in the dictionary, we can reference the bullet type from that dictionairy
if (bulletLibrary.ContainsKey(tagString))
{
print("spawn: " + bulletLibrary[tagString].bulletName);
print("prefab: " + bulletLibrary[tagString].prefab);
//all the data you need is in: bulletLibrary[tagString];
//Bullet.Bullet(bulletLibrary[tagString]);
other.gameObject.SetActive(false);
}
}
Sidenote: If you spawn a lot of bullets, you can use pooling. SimplePool is nice and easy for this. Instead of calling: instantiate and destroy, you call: SimplePool.Spawn() and SimplePool.DeSpawn().
If you have any more questions on this feel free to ask ;)

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);
}
}

Problem with Colliders and their rotation in the Unity Game

The problem is that I what to create an openable door. This door should open when the player enter the Box Collider which is connected to the door. But the problem is when the door begins to open and to rotate, Collider starts to rotate too which brings me a lot of problems with usind such an idea. I try to create EmptyObject with its Collider but I can't connect this Collider with script and OnTriggerEnter function itself. Maybe I don't understand something, who knows, I'm just a begginer. How knows how to help, please write an answer.
My code if somebody needs it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class openDoor : MonoBehaviour {
public Vector3 Rotation_;
private int i;
public float speed;
bool opentheDoor;
bool closetheDoor;
// Use this for initialization
void Start () {
opentheDoor = false;
closetheDoor = false;
}
// Update is called once per frame
void Update () {
if (opentheDoor == true) {
this.transform.Rotate (Rotation_ * Time.deltaTime * speed);
i += 1;
if (i == 70) {
opentheDoor = false;
i = 0;
}
}
if (closetheDoor == true) {
this.transform.Rotate (-Rotation_ * Time.deltaTime * speed);
i += 1;
if (i == 70) {
closetheDoor = false;
i = 0;
}
}
}
void OnTriggerEnter (Collider other) {
if (other.gameObject.tag == "Player") { {
opentheDoor = true;
}
}
}
void OnTriggerExit (Collider other) {
if (other.gameObject.tag == "Player") {
closetheDoor = true;
}
}
}
This is how i would handle the scenerio
Take
DoorHandler.cs
public class DoorHandler : MonoBehaviour {
public Door door;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
door.OpenDoor();
}
}
}
This should be attached to Parent of the door.
Next Take
Door.cs
public class Door : MonoBehaviour {
public bool isOpened = false;
public void OpenDoor()
{
if (!isOpened)
{
isOpened = true;
Debug.Log("OPEN");
//OPEN DOOR CODE!
}
}
}
Attach this to the Door GameObject
NOTE
The hierarchy would be like DoorHandler->Door->DoorModel (where Door is just an empty gameobject pivot of the Door)
In DoorHandler GameObject attach BoxCollider and Check Mark IsTrigger.
Also Player SHOULD HAVE A RIGIDBODY (preferably Kinametic) and obviously a collider
So When Player enters the DoorHandler's Collider -> The DoorHandler's OnTriggerEnter will be triggered and finally Call the Door to OpenDoor()
Add another check in OnTriggerEnter that checks if the door is currently opening or not.
void OnTriggerEnter (Collider other) {
if (other.gameObject.tag == "Player" && !opentheDoor) {
opentheDoor = true;
}
}
attach the door to an empty object. put the trigger on the empty object. then make the ontrigger entry rotate the door, not the paent object, and the collider will remain in place.
Parent
-child(door)
-child(collider)

Unity colision will not execute any logic

A simple script doing a simple thing. Yet no matter what I cannot get it script to work.
using UnityEngine;
using System.Collections;
public class ShotScript : MonoBehaviour {
public Player pScript;
private Rigidbody2D shotRigid;
public bool enemyContact = false;
public bool enemyContactTrue = false;
void Awake() {
shotRigid = GetComponent<Rigidbody2D> ();
}
void Start() {
shotRigid = GetComponent<Rigidbody2D> ();
}
void enemyContactFunction() {
enemyContact = true;
}
void OnCollisionEnter2D (Collision2D col) {
if (col.gameObject.tag == "Enemy1" ) {
Debug.Log ("shot has collided with tagged enemy");
if (enemyContact == false){
enemyContactFunction();
}
}
}
}
The debugs will go off but nothing ever happens in the game and this it taking me days to figure out. How would anyone else make something, anything happen, after a collision like this work when mine does not?

Unity3d Transform.LookAt also changes position

Title says it all.
I provided an NPC with the following script, which should make him look and bark at the player.
When the player comes into the NPC's reach, however, the NPC starts walking towards the player instead of just facing him.
Any thoughts?
using UnityEngine;
public class Barking : MonoBehaviour {
public AudioSource barkingAudio;
private GameObject player;
private bool barking;
void Start () {
player = GameObject.FindGameObjectWithTag("Player");
barking = false;
}
void Update () {
if (barking)
lookAtPlayer();
}
private void lookAtPlayer()
{
transform.LookAt(player.transform.position, Vector3.up);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject == player)
{
barking = true;
barkingAudio.mute = false;
barkingAudio.Play();
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject == player) {
barking = false;
barkingAudio.mute = true;
barkingAudio.Stop();
}
}
}
Since I was using a Rigidbody and rotating the transform manually, there was some unexpected behaviour.
I found some code online which I could replace the Transform.LookAt method with:
var qTo = Quaternion.LookRotation(player.transform.position - transform.position);
qTo = Quaternion.Slerp(transform.rotation, qTo, 10 * Time.deltaTime);
GetComponent<Rigidbody>().MoveRotation(qTo);
This fixed my problem!