instances executing at the same time(solved)
I trigger a method on one instance of a script and all the instances of the script execute at once?
I use it on 4 objects here is the code
using UnityEngine;
public class Pikup : MonoBehaviour {
public GameObject pikup;
public Camera Plar;
public GameObject pickupic;
public Item itemtobepickupt;
void Update()
{
RaycastHit hit;
if (Physics.Raycast(Plar.transform.position, Plar.transform.forward, out hit))
{
Pikup pikup = hit.transform.GetComponent<Pikup>();
if (pikup != null)
{
pickupic.SetActive(true);
}
else
{
pickupic.SetActive(false);
}
if (pikup != null && Input.GetButtonDown("E")) {
PickupItem();
}
}
}
void PickupItem ()
{
pickupic.SetActive(false);
bool wasPickedUp = Invtorey.instancs.Add(itemtobepickupt);
if (wasPickedUp)
Destroy(gameObject);
}
}
thanks
Please provide code and description where, how and on how many objects you use the script on.
Answer by shakecaine · Nov 26, 2017 at 10:57 AM
Of course they execute all at once. To start with please, please for the love of us all read through manual: https://docs.unity3d.com/Manual/index.html
Answer is very simple. You hit object with raycast, pikup is not null and you have E button clicked. Each of the objects that has the script does not care if it was the object that was hit, so all of them execute same code as all conditions are fulfilled. For all of the objects these conditions in if statement are true, so code executes.
If you want to detect collision i recommend using OnCollisionEnter instead as that code will only execute when something collides with your collider. For now you just send 4x rays each frame. Have raycasting on the player instead and handle colliders on objects.
If you can, please mark my answer as best answer to your question.
Your answer
Follow this Question
Related Questions
Is it possible to customize how a variable of a certain type would look in the inspector? 1 Answer
How to create a new instance of an object? 0 Answers
Different methods for instances of a ScriptableObject 0 Answers
Accessing decal's material's parameters in animation window. 0 Answers
UI button click to trigger functions in multiple instances 0 Answers