How to stop object on physics conveyor with the help of VR button? - c#

I am making a basic VR model. In this model, Object are travelling in physics conveyor.
My problem is to reduce speed of conveyor with the help of VR button.
I want when I click VR button then speed become zero and object should stopped in conveyor and again when click VR button then speed become one and object start travelling in conveyor.
But it is not working. I think there is a fault in my coding. I am trying to do this: when I click VR button the object should stopped in conveyor and when again I clicked VR button then object start travelling.
I have attached my coding:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class Conveyor : MonoBehaviour
{
public GameObject belt;
public Transform endpoint;
public float speed;
public GameObject button;
public UnityEvent onPress;
public UnityEvent onRelease;
GameObject press3;
bool isPressed;
void Start()
{
}
void OnTriggerStay(Collider other)
{
other.transform.position = Vector3.MoveTowards(other.transform.position, endpoint.position,speed * Time.deltaTime);
}
private void OnTriggerEnter(Collider other)
{
if(isPressed != press3)
{
button.transform.localPosition = new Vector3(0,0.015f,0);
press3 = button;
speed = 1;
onPress.Invoke();
isPressed =true;
}
}
private void OnTriggerExit(Collider other)
{
if(isPressed = press3)
{
button.transform.localPosition =new Vector3(0,0.02f,0);
speed =0;
onRelease.Invoke();
isPressed =false;
}
}
}

Related

Game object can't detect others when using collision.gameObject.tag in unity

I have designed a scenario as below:
I created an object spawner to collide with things tagged as "ob", using a boolean to manage the timing to spawn new obstacles. Nonetheless, after some testing, I found that it seemed like nothing had ever collided with one another(Judged by the strings I put in the if condition had never shown in the console.) Can't figure out why! Please HELP!!!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class newObSpawning : MonoBehaviour
{
public GameObject[] oblist;
private bool hasOb=true;
public float adjustSpawnx;
void Update()
{
if (!hasOb)
{
spawnObs();
hasOb = true;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("ob"))
{
hasOb = true;
Debug.Log("hasOb"); //just for testing
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("ob"))
{
hasOb = false;
Debug.Log("hasOb");
}
}
public void spawnObs()
{
int i = Random.Range(0, oblist.Length);
Debug.Log(i);
float y = 7.87f;
GameObject newob = Instantiate(oblist[i], new Vector3(transform.position.x+ adjustSpawnx,y,0), Quaternion.identity);
}
}
obspawner carry a "follow player" script to move at the same pace as the player,and it went just well
Your player doesn't seem to have a Rigidbody2D component. Add Rigidbody2D to your player. A collider can only emit OnTriggerEnter2D or OnTriggerExit2D events if there is a rigidbody on the object too
You have to tag the object "ob" that you want to register the collision with, most probably, I think what you are searching for is the collision of your player with object spawner so tag the player with "ob".

Animation keeps getting triggered when I step on the tiles

I'm developing a TopDown 2D game on Unity with some RPG elements and I did as so, when the player steps on a set of tiles placed on the map, it triggers an animation with a UI showing some text. However, the animation gets called multiple times while the player keeps stepping on the tiles and even when he exits the trigger area.
What I need help with is how to make the animation only trigger once and, while the UI is in on the screen, the player is not allowed to move until the player presses the button in the UI (already programmed and working).
Here is the code I used to make the trigger function:
public class TriggerScript : MonoBehaviour
{
public string popUp;
public Animator animator;
void Start()
{
animator = GetComponent<Animator>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
pop.PopUp(popUp);
Debug.Log("trigger");
animator.SetTrigger("pop");
}
}
And here is the PopUpSystem that sets the text:
public class PopUpSystem : MonoBehaviour
{
public GameObject popUpBox;
public Animator popupanimation;
public TMP_Text popUpText;
public void PopUp(string text)
{
popUpBox.SetActive(true);
popUpText.text = text;
popupanimation.SetTrigger("pop");
}
}
If, in order to help me, you need more information and details, please ask me in the comment section.
Note that I am new to Unity and have zero experience with it so, if you can be patient and explain things in a simple way, I would enjoy that!
Thank you for reading.
Edit: this is the animator window:
Edit 2: The code that I use for the movement of the player:
public class PLayerController : MonoBehaviour
{
private Rigidbody2D MyRB;
private Animator myAnim;
public string popUp;
[SerializeField]
private float speed;
// Start is called before the first frame update
void Start()
{
MyRB = GetComponent<Rigidbody2D>();
myAnim = GetComponent<Animator>();
}
private void Move()
{
myAnim.SetTrigger("popUp");
}
// Update is called once per frame
void Update()
{
MyRB.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) * speed * Time.deltaTime;
myAnim.SetFloat("moveX", MyRB.velocity.x);
myAnim.SetFloat("moveY", MyRB.velocity.y);
if ((Input.GetAxisRaw("Horizontal")==1) ||(Input.GetAxisRaw("Horizontal") == -1)||(Input.GetAxisRaw("Vertical") == 1)||(Input.GetAxisRaw("Vertical") == -1))
{
myAnim.SetFloat("LastMoveX", Input.GetAxisRaw("Horizontal"));
myAnim.SetFloat("LastMoveY", Input.GetAxisRaw("Vertical"));
}
}
}
Edit 3: Code with boolean:
public class TriggerScript : MonoBehaviour
{
public string popUp;
public Animator animator;
bool condition = false;
void Start()
{
animator = GetComponent<Animator>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (condition == false)
{
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
pop.PopUp(popUp);
Debug.Log("trigger");
animator.SetTrigger("pop");
condition = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
animator.SetTrigger("close");
}
All you have to do is to set your TriggerScript to something like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TriggerScript : MonoBehaviour
{
public string popUp;
private void OnTriggerEnter2D(Collider2D collision)
{
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
if (collision.gameObject.tag == "Player")
{
pop.PopUp(popUp);
}
}
private void OnTriggerExit2D(Collider2D collision)
{
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
pop.closeBox();
}
}
and then set your PopUpSystemScript to something like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PopUpSystem : MonoBehaviour
{
public GameObject popUpBox;
public Animator popupanimation;
public TMP_Text popUpText;
public void PopUp(string text)
{
popUpBox.SetActive(true);
popUpText.text = text;
popupanimation.SetTrigger("pop");
}
public void closeBox()
{
popupanimation.SetTrigger("close");
}
}
Now click on the popUp and close animation clips (in Animations folder) and remove the Loop Time check mark. and you should be all set to see the animation appears and disappears.
To stop the player, you can either use Time.timeScale. or set the rigidbody to isKenimatic.

Beginner having Problems with Restarting Scenes when Dying in Unity

so I’m trying to create a respawn system as a beginner, and everything seems to be working the first time but the second time it seems to be unbehaving. If anyone knows how to help me, I would appreciate it
LevelControl:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelControl : MonoBehaviour
{
public int index;
public string levelName;
public GameObject GameOverPanel;
public static LevelControl instance;
private void Awake()
{
if (instance == null)
{
DontDestroyOnLoad(gameObject);
instance = GetComponent<LevelControl>();
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
//Loading level with build index
SceneManager.LoadScene(index);
//Loading level with scene name
SceneManager.LoadScene(levelName);
//Restart level
//SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
public void LoadLevel1()
{
SceneManager.LoadScene("Game");
}
public GameObject GetGameOverScreen()
{
return GameOverPanel;
}
}
PlayerMovement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController2D controller;
public float runSpeed = 40f;
float horizontalMove = 0f;
bool jump = false;
bool crouch = false;
// Update is called once per frame
void Update()
{
horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
if (Input.GetButtonDown("Jump"))
{
jump = true;
}
if (Input.GetButtonDown("Crouch"))
{
crouch = true;
}
else if (Input.GetButtonUp("Crouch"))
{
crouch = false;
}
}
void FixedUpdate()
{
// Move our character
controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
jump = false;
//FindObjectOfType<GameManager>().EndGame();
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Enemy")
{
//Destroy(FindObjectOfType<CharacterController2D>().gameObject);
GameObject.Find("Player").SetActive(false);
LevelControl.instance.GetGameOverScreen().SetActive(true);
}
}
}
Error In Unity Video: https://imgur.com/a/Sr0YCWk
If your wondering what I'm trying to do, well, when the 2 colliders of the Player and Enemy collide, I want a restart button to pop up, and the Character to get destroyed, and after that restart the level as is.
You didn't provide much but I try to work with what we have.
In LevelController you have
private void Awake()
{
if (instance == null)
{
DontDestroyOnLoad(gameObject);
instance = GetComponent<LevelControl>();
}
}
First of all just use
instance = this;
;)
Then you are doing
LevelControl.instance.GetGameOverScreenn().SetActive(true);
I don't see your setup but probably GetGameOverScreenn might not exist anymore after the Scene reload while the instance still does due to the DontDestroyOnLoad.
Actually, why even use a Singleton here? If you reload the entire scene anyway you could just setup the references once via the Inspector and wouldn't have to worry about them later after scene changes...
Also
GameObject.Find("Player").SetActive(false);
seems odd .. isn't your PlayerController attached to the Player object anyway? You could just use
gameObject.SetActive(false);
Ok, Normally it would be easier just to do this:
if (collision.gameObject.tag == "Enemy")
{
//Destroy(FindObjectOfType<CharacterController2D>().gameObject);
gameObject.SetActive(false);
LevelControl.instance.GetGameOverScreen().SetActive(true);
But this will NOT work if you want to attach the script to any other gameobjects for any reason. If you are then first make a game object variable containing the player, like this:
public GameObject Player = GameObject.Find("Player");
Then say
Player.SetActive(false);
This creates a player gameobject which you can access by calling the variable.

Object is not triggering collider

Hi my problem is in Unity, I am a beginner in c#, my gameObject is not triggering the collider that is set on the plane of the game, in order for it to reset it's position.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BasketballSpawnScript : MonoBehaviour
{
public Transform respawnPoint;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Basketball"))
{
other.gameObject.transform.position = respawnPoint.position;
}
}
}
This script is attached to the plane and the gameobject is tagged with Basketball, when it enters the collider of the floor it should transform it's position to the original position.
I cannot see what is wrong, can I receive some help?
P.S I get this error when other gameobject go through the collider too.
NullReferenceException: Object reference not set to an instance of an object
If using a Transform for spawn point, remember to set the value of it in the inspector menu.
public Transform respawnPoint;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Basketball"))
other.transform.position = respawnPoint.position;
}
else
public Vector3 respawnPoint = Vector3.zero;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Basketball"))
other.transform.position = respawnPoint;
}
private void OnTriggerEnter(Collider other){
if(other.gameobject.tag=="Basketball"){
other.gameobject.transform.position = respawnPoint;
}
}
I hope it helps you.

Unity 2D box collider to call and run C# script

I have a camera shake C# script that I want to run once the player triggers a box collider?
The camera shake code:
using UnityEngine;
using System.Collections;
public class CameraShake : MonoBehaviour
{
public Transform camTransform;
public float shake = 0f;
public float shakeAmount = 0.7f;
Vector3 originalPos;
void Awake()
{
if (camTransform == null)
{
camTransform = GetComponent(typeof(Transform)) as Transform;
}
}
void OnEnable()
{
originalPos = camTransform.localPosition;
}
void Update()
}
That's because you did not add the OnTriggerEnter, OnTriggerStay or OnTriggerExit ( depending of what you want to achieve ) function to the script.
For e.g:
void OnTriggerEnter(Collider other){
if(other.tag == "Player"){
// shake the camera here..
}
}
Don't forget to check the trigger box in the box collider.

Categories