Hey Everyone,
I am trying to implement a game where the player can pickup some objects and place them somewhere else. I need the player to pick one object at a time. I wrote some code to implement this but it is not working properly can anyone help me.
problem : The code works perfectly for only one object and gives trouble for other objects.
The below code is for the player object :
public LayerMask layers;
public ObjectControler [] scripts;
public float rayDistance;
public KeyCode pickWith = KeyCode.P;
bool ray;
bool held;
private void Update()
{
ray = Physics.Raycast(transform.position, transform.forward, rayDistance, layers);
for (int i = 0; i < scripts.Length; i++)
{
if (ray && !held && Input.GetKeyDown(pickWith) && !scripts[i].isTriggered)
{
scripts[i].isTriggered = true;
held= true;
}
else if (held && scripts[i].isTriggered && Input.GetKeyDown(pickWith))
{
scripts[i].isTriggered = false;
held = false;
}
}
}
The below code is for the objects that the player can pick :
public GameObject objectHolder;
public Transform objectTransform;
public bool isTriggered;
Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
}
private void Update()
{
if(isTriggered && transform.parent!=objectHolder)
{
AttachToParent();
}
if (isTriggered)
{
rb.position=objectTransform.position;
}
else if(!isTriggered)
{
transform.SetParent(null);
}
}
void AttachToParent()
{
transform.SetParent(objectHolder.transform);
}
I think the problem is on the player’s code where i used a for loop to traverse among the scripts i had. Can anyone please solve this issue.