One GameObejct script affecting another GameObject of the same prefab
Hey guys,
So basically I'm trying to develop an interactive system where the player can interact with certain objects, in this case, is just a chest that can be opened by the player.
I have a prefab that contains the chest and the script that controls it.
I'd like to ask why my code would affect another GameObject of my prefab and why is it affecting globally since it has nothing to do with it.
This is my PlayerController script:
private bool _canOpenChest;
private ChestBehaviour _chest = null;
private void interactions()
{
if (_canOpenChest && Input.GetKey(_keyInteract) && _chest != null)
{
_chest.Open();
}
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == Constants.Collectable_Chest)
{
_chest = other.GetComponent<ChestBehaviour>();
_canOpenChest = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.tag == Constants.Collectable_Chest)
{
_chest = null;
_canOpenChest = false;
}
}
And my Chest script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChestBehaviour : MonoBehaviour
{
Animator _animator;
private bool _open;
void Start()
{
this._animator = GetComponent<Animator>();
this._open = false;
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
if (!this._open && other.tag == "Player")
{
Shake();
}
}
private void OnTriggerExit(Collider other)
{
if (!this._open && other.tag == "Player")
{
Stop();
}
}
private void Stop()
{
this._animator.SetInteger("State", 0);
}
private void Shake()
{
this._animator.SetInteger("State", 1);
}
public void Open()
{
if (!this._open)
{
print("opened");
this._animator.SetInteger("State", 2);
this._open = true;
}
}
}
Also, if there is a better way to do my interaction system just let me know.
Your answer
Follow this Question
Related Questions
Mesh missing in prefab 0 Answers
Variables in a script on a prefab do not store runtime changes 0 Answers
How to Create variants with different scripts interact with player 1 Answer
Standard Assets unusable - Trying to use the ThirdPersonController Prefab 1 Answer
OnClick() event script from a prefab 0 Answers