Home > Software design >  My Coroutine Will Not Work. How Can I Fix It?
My Coroutine Will Not Work. How Can I Fix It?

Time:07-01

I am trying to make a game but when i was coding an aspect it didnt work. So basically, when you enter the trigger, the coffee cup should be in your hands and follow you. I tried to use a coroutine and while loop to do this.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GrabCoffee : MonoBehaviour
{
    // Start is called before the first frame update
    public Vector3 pos;
    public GameObject coffee;
    void Awake()
    {
    pos = coffee.transform.position;
    }
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        
    }

    IEnumerator grabbing()
    {
        while (true)
        {
        yield return new WaitForSeconds(0.1f);
        pos = new Vector3(pos.x,0.813f,pos.x);
        }
    }
    
    void OnTriggerEnter(Collider collider)
    {
    StartCoroutine(grabbing()); 
    }
}

when I collide with this i just go through it and nothing happens

CodePudding user response:

Consider parenting the coffee cup to the hand object. If you don't have a hand object, add an empty game object to the character as child and place it at the hand position.

When you enter the trigger, parent the cup under the hand object and set its position to Vector3.zero

public Transform hand;
public Transform coffee;
void OnTriggerEnter(Collider collider)
{
    coffee.SetParent(hand);
    coffee.localPosition = Vector3.zero;
}

CodePudding user response:

You have your issue because of two reasons:

  • not setting the position to an object. Your pos value is just a position, not the position of the object. You need to assign the new position to the cup's gameObject.transform.position.
  • actually, even if you will assign a new position to your object, it will not move at all, as you always set the same position to it (new Vector3(pos.x,0.813f,pos.x) will always have the same value)

So, you have at least two options:

  • sync cup position with the hand position (you can use collider variable in the OnTriggerEnter method to get the target position by using collider.gameObject.transform.position, store it, and sync your cup gameObject.transform.position with it in the Update method)
  • as Everts mentioned in his answer, you can add your cup as a child to the hand, then it will move with the hand automatically.

Actually, you should decide what you want to achieve to be able to choose the correct option for your case.

  • Related