How To Change CineMachine Dead Zone Width With Code? UNITY - unity3d

So I was wondering how I could change my dead zone width or height with coding I have a collision detector so when my player collides with that rectangle I want to change the dead zone width to 2 but I have no idea on how to do this I tried to search online for an answer but couldn't so I wanted to ask here to see if anyone knows the answer.
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("dead"))
{
Debug.Log("Dead Zone Width Changed");
}
}
Rest of My Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class stopcamera : MonoBehaviour
{
public CinemachineVirtualCamera cam;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("dead"))
{
var composer = cam.GetCinemachineComponent<CinemachineComposer>();
composer.m_DeadZoneWidth = 2f;
Debug.Log("saman the third");
}
}
}

I want to change the dead zone width to 2
To change a specific value of your Cinemachine virtual camera. You first need to get the ComponentBase of either (Aim, Body, or Noise), depending on which stage you want to change the values at. You can do that with GetCinemachineComponent(CinemachineCore.Stage.Body).
To then change the value you need to ensure the type your ComponentBase is set to the same value as in the Inspector. In your case that would be the CineMachineFramingTransposer.
Example:
[SerializeField]
private CinemachineVirtualCamera virtualCam;
private CinemachineComponentBase componentBase;
private void Start() {
// Get the componentBase of our virutalCam to adjust its values via code.
componentBase = virtualCam.GetCinemachineComponent(CinemachineCore.Stage.Body);
}
private void OnTriggerEnter2D(Collider2D other) {
if (!other.gameObject.CompareTag("dead")) {
return;
}
// Check if the CinemachineCore.Stage.Body ComponentBase,
// is set to the CinemachineFramingTransposer.
if (componentBase is CinemachineFramingTransposer) {
var framingTransposer = componentBase as CinemachineFramingTransposer;
// Now we can change all its values easily.
framingTransposer.m_DeadZoneWidth = 2f;
Debug.Log("Dead Zone Width Changed");
}
}

Related

load Scene with Script but it turns Black

I've done it so far that when my player dies the level is restarted and I've written everything in the script but when I try it and the scene is reloaded everything is somehow extremely dark compared to before, although all settings from the camera etc. are the same and I don't know if I'm doing something wrong or if it's a bug
my Script:
public class GameManager : MonoBehaviour
{
public GameObject enemyPrefab;
// Start is called before the first frame update
void Start()
{
GameObject player = GameObject.Find("Player");
SpawnEnemy();
}
// Update is called once per frame
void Update()
{
RestartGame();
}
void RestartGame()
{
if(GameObject.Find("Player").GetComponent<PlayerMovement>().playerHealth <= 0)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
You need to bake your lighting inside your scene. Here are instructions on how:
Head to Window > Rendering > Lighting
Press Generate Lighting (Make sure Auto Generate is unselected)
Source
Your code has some trouble. But I'm not going to fix rotation issues. But here your working sample:
public class GameManager : MonoBehaviour {
public GameObject enemyPrefab;
// Start is called before the first frame update
void Start()
{
GameObject player = GameObject.Find("Player");
SpawnEnemy();
}
// Update is called once per frame
void Update()
{
RestartGame();
}
bool navigated = false;
void RestartGame()
{
if (!navigated)
{
if(GameObject.Find("Player").GetComponent<PlayerMovement>().playerHealth <= 0)
{
navigated = true;
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
}
}

How to set the position of a gameobject into initial position after grabbing ended using hand in SteamVR using Unity?

Pretty new to VR.I took a gameobject from an intial position by grabbing.When I grab a helmet and touch my body collider it hides the helmet.So next I may pick glasses and apply it to my body(Hides the GameObject).Next when I put the Incorrect Helmet the first helmet should go back to its initial position and should be seen in the scene.Similarily there are many GameObjects in the scene
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Helmet")
{
HideGameObject();
}
if (other.gameObject.tag == "Glasses")
{
HideGameObject();
}
if (other.gameObject.tag == "EarMuff")
{
HideGameObject();
}
if (other.gameObject.tag == "IncorrectHelmet")
{
HideGameObject();
}
if (other.gameObject.tag == "IncorrectGlasses")
{
HideGameObject();
}
if (other.gameObject.tag == "IncorrectEarMuff")
{
HideGameObject();
sendPickValues.Invoke(2, 0);
}
}
//Another script to set the GameObjects position
public class BackToPosition : MonoBehaviour
{
private Vector3 initialPosition;
private Quaternion initialRotation;
GameObject prevObject;
GameObject currObject;
// Start is called before the first frame update
void Start()
{
initialPosition = transform.position;
initialRotation = transform.rotation;
}
// Update is called once per frame
void Update()
{
}
public void BackToInitialPosition()
{
Debug.Log("Entered");
transform.position = initialPosition;
transform.rotation = initialRotation;
}
}
I am not trying to set the previous grabbed object to initial position.I may select wrong helmet first and pick many other matching gameobjects and later change to correct helmet.At that time first helmet should go to initial position.
This is a script that I use in SteamVR to grab and release a boat's rudder handle but it should be usable for you too:
[RequireComponent(typeof(Interactable))]
public class HandAttacher : MonoBehaviour
{
public UnityEvent OnGrab;
public UnityEvent OnRelease;
public UnityEvent OnHandEnter;
public UnityEvent OnHandLeave;
private Interactable interactable;
void Awake()
{
interactable = GetComponent<Interactable>();
}
/// this magic method is called by hand while hovering
protected virtual void HandHoverUpdate(Hand hand)
{
GrabTypes startingGrabType = hand.GetGrabStarting();
if (interactable.attachedToHand == null && startingGrabType != GrabTypes.None)
{
hand.AttachObject(gameObject, startingGrabType, Hand.AttachmentFlags.DetachFromOtherHand | Hand.AttachmentFlags.ParentToHand);
OnGrab?.Invoke();
}
}
protected virtual void OnHandHoverBegin(Hand hand)
{
OnHandEnter?.Invoke();
}
protected virtual void OnHandHoverEnd(Hand hand)
{
OnHandLeave?.Invoke();
}
protected virtual void HandAttachedUpdate(Hand hand)
{
if (hand.IsGrabEnding(gameObject))
{
hand.DetachObject(gameObject);
OnRelease?.Invoke();
}
}
}
Basically it creates Unity Events that you can add Listeners to in the Editor's Inspector window, or in code.
So in your use case, I would add a listener to OnRelease, and reset the GameObject's position and rotation to whatever it was before.
I tried using BackToPosition or something similar in Update comparing the original position to its current to reset the object's position, and the object keeps resetting on a loop instead of resetting to its original position and stopping.

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 - NullReferenceException in my GameOverManager

Iam trying to load my "PlayerHealth" Script to my "GameOverManager" to check my currentHealth from the PlayerHealth-Script.
If the current health is "0" - I want to trigger an animation.
The problem is, that Unity gives me an error with following message:
"NullReferenceException: Object reference not set to an instance of an object
GameOverManager.Update () (at Assets/GameOverManager.cs:32)"
Here is the piece of Code of my GameOverManager:
public class GameOverManager : MonoBehaviour {
public PlayerHealth playerHealthScript;
public float restartDelay = 5f;
Animator anim;
float restartTimer;
private void Awake()
{
anim = GetComponent<Animator>();
}
private void Update()
{
playerHealthScript = GetComponent<PlayerHealth>();
if (playerHealthScript.currentHealth <= 0) {
anim.SetTrigger("GamerOver");
restartTimer += Time.deltaTime;
if (restartTimer >= restartDelay) {
SceneManager.LoadScene(2);
}
}
}
}
The error is triggered on the following line:
if (playerHealthScript.currentHealth <= 0)
Here is the hierarchy - FPSController holds "PlayerHealth" - HUDCanvas holds "GameOverManager:
Here are the inspectors:
Here is the code of "PlayerHealth":
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;
public class PlayerHealth : MonoBehaviour
{
public int startingHealth = 100; // The amount of health the player starts the game with.
public int currentHealth; // The current health the player has.
public Slider healthSlider; // Reference to the UI's health bar.
public Image damageImage; // Reference to an image to flash on the screen on being hurt.
public AudioClip deathClip; // The audio clip to play when the player dies.
public float flashSpeed = 5f; // The speed the damageImage will fade at.
public Color flashColour = new Color(1f, 0f, 0f, 0.1f); // The colour the damageImage is set to, to flash.
public float restartDelay = 5f;
//Animator anim; // Reference to the Animator component.
public AudioSource playerAudio; // Reference to the AudioSource component.
// PlayerMovement playerMovement; // Reference to the player's movement.
// PlayerShooting playerShooting; // Reference to the PlayerShooting script.
bool isDead; // Whether the player is dead.
bool damaged; // True when the player gets damaged.
void Awake()
{
// Setting up the references.
// anim = GetComponent<Animator>();
// playerAudio = GetComponent<AudioSource>();
// playerMovement = GetComponent<PlayerMovement>();
// playerShooting = GetComponentInChildren<PlayerShooting>();
// Set the initial health of the player.
currentHealth = startingHealth;
}
void Update()
{
// If the player has just been damaged...
if (damaged)
{
// ... set the colour of the damageImage to the flash colour.
damageImage.color = flashColour;
}
// Otherwise...
else
{
// ... transition the colour back to clear.
damageImage.color = Color.Lerp(damageImage.color, Color.clear, flashSpeed * Time.deltaTime);
}
// Reset the damaged flag.
damaged = false;
}
public void TakeDamage(int amount)
{
// Set the damaged flag so the screen will flash.
damaged = true;
// Reduce the current health by the damage amount.
currentHealth -= amount;
playerAudio.Play();
Debug.Log("PLayer Health: " + currentHealth);
// Set the health bar's value to the current health.
healthSlider.value = currentHealth;
// Play the hurt sound
playerAudio.Play();
// If the player has lost all it's health and the death flag hasn't been set yet...
if (currentHealth <= 0 && !isDead)
{
// ... it should die.
Death();
}
}
void Death()
{
// Set the death flag so this function won't be called again.
isDead = true;
Debug.Log("In der Death Funktion");
First of all, you don't need, or better, you SHOULD NOT, use GetComponent inside Update, it's a very slow method and it impacts a lot the performance.
So, change your code to this:
public class GameOverManager : MonoBehaviour {
public PlayerHealth playerHealthScript;
public float restartDelay = 5f;
private Animator anim;
private float restartTimer;
private void Awake() {
anim = GetComponent<Animator>();
//No need for GetComponent<PlayerHealth>() if you assign it in the Inspector
//playerHealthScript = GetComponent<PlayerHealth>();
}
private void Update() {
if (playerHealthScript.currentHealth <= 0) {
anim.SetTrigger("GamerOver");
restartTimer += Time.deltaTime;
if (restartTimer >= restartDelay) {
SceneManager.LoadScene(2);
}
}
}
}
Moreover, your bug happens most probably because in the Inspector you assigned to the playerHealthScript variable the game object containing the PlayerHealth script. But, since you try in Update to get the script component again but this time from the game object that has the GameOverManager script (and I assume it doesn't have the PlayerHealth script), you get the NullReference since that script can't be found on this game object.
So, as you can see from the two lines commented out in my code, you actually don't need to get that component from script, just assign it via Inspector and you're good to go.

Script code only seems to work on single instance of prefb

I am experiencing the strangest issue
I have a ray cast and when it touches a certain layer it calls my function which does a small animation.
The problem is, this only works on a single object, I have tried duplicating, copying the prefab, dragging prefab to the scene, it doesn't work.
Now I have this code below, and as you can see I have this line which allows me to access the script on public PlatformFall platfall; so I can call platfall.startFall();
Something I've noticed, If I drag a single item from the hierarchy to the public PlatFall in Inspector then that SINGLE object works as it should. ( in that it animates when startFall is called). HOWEVER, if I drag the prefab from my project to the inspector then they do not work. (Even if debug log shows that the method is called animation does not occur).
public class CharacterController2D : MonoBehaviour {
//JummpRay Cast
public PlatformFall platfall;
// LayerMask to determine what is considered ground for the player
public LayerMask whatIsGround;
public LayerMask WhatIsFallingPlatform;
// Transform just below feet for checking if player is grounded
public Transform groundCheck;
/*....
...*/
Update(){
// Ray Casting to Fallingplatform
isFallingPlatform = Physics2D.Linecast(_transform.position, groundCheck.position, WhatIsFallingPlatform);
if (isFallingPlatform)
{
Debug.Log("Here");
platfall.startFall();
}
Debug.Log(isFallingPlatform);
}
}
Platform Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformFall : MonoBehaviour
{
public float fallDelay = 0.5f;
Animator anim;
Rigidbody2D rb2d;
void Awake()
{
Debug.Log("Awake Called");
anim = GetComponent<Animator>();
rb2d = GetComponent<Rigidbody2D>();
}
private void Start()
{
Debug.Log("Start Called");
}
//void OnCollisionEnter2D(Collision2D other)
//{
// Debug.Log(other.gameObject.tag);
// GameObject childObject = other.collider.gameObject;
// Debug.Log(childObject);
// if (other.gameObject.CompareTag("Feet"))
// {
// anim.SetTrigger("PlatformShake");
// Invoke("Fall", fallDelay);
// destroy the Log
// DestroyObject(this.gameObject, 4);
// }
//}
public void startFall()
{
anim.SetTrigger("PlatformShake");
Invoke("Fall", fallDelay);
Debug.Log("Fall Invoked");
// destroy the Log
// DestroyObject(this.gameObject, 4);
}
void Fall()
{
rb2d.isKinematic = false;
rb2d.mass = 15;
}
}
I understood from your post that you are always calling PlatformFall instance assigned from inspector. I think this changes will solve your problem.
public class CharacterController2D : MonoBehaviour {
private PlatformFall platfall;
private RaycastHit2D isFallingPlatform;
void FixedUpdate(){
isFallingPlatform = Physics2D.Linecast(_transform.position, groundCheck.position, WhatIsFallingPlatform);
if (isFallingPlatform)
{
Debug.Log("Here");
platfall = isFallingPlatform.transform.GetComponent<PlatformFall>();
platfall.startFall();
}
}
}
By the way, i assume that you put prefab to proper position to cast. And one more thing, you should make physics operations ,which affect your rigidbody, in FixedUpdate.