- Home /
Component passing self to method
I have a component called ItemSpot which is a container for an object of type Pickupable. When the player clicks on the ItemSpot, the item in the container is supposed to move from the spot to the player and the items reference is supposed to be "moved" from the spot to the PlayerController.
This is my code:
public void OnClick(PlayerController player)
{
// Pick up items
if (player.HeldItem == null && Item != null)
{
// Attach item to own transform
Item.transform.parent = player.HandTransform;
// disable input to prevent glitches while taking an item in hand
player.InputDisabled = true;
// Coroutines on the Item that moves the gameObject with an animation
StartCoroutine(Item.MoveTowards(player.HandTransform.position));
StartCoroutine(Item.TurnTowards(player.HandTransform.rotation));
Debug.Log(player.gameObject);
// Move Item reference from Spot to player
player.HeldItem = Item;
Item = null;
// reenable input after some time
IEnumerator coroutine () {
yield return new WaitForSeconds(player.HeldItem.animationTime);
player.InputDisabled = false;
}
StartCoroutine(coroutine());
}
}
This bit is called from the PlayerController with itemSpot.OnClick(this)
Moving the GameObject works absolutely fine, but the references to the item do not change at all. Weirdly, Debug.Log(player.HeldItem) inside this function returns the correct reference, but in the PlayerController Component it is still null.
I suspect that this has something to do with m usage of the this operator, but I can't figure out how to properly pass a reference to self.
The most baffling thing to me is, that the ItemSpot is not able to set its own private field to null
Answer by fritzlloydw · Nov 25, 2021 at 12:30 PM
I found the solution and the issue is, of course, my own stupidity.
Just below the code I posted, I have the behaviour for passing back an item from the Player to the Itemspot. In it, I check, whether the Player has an Item in hand and the Itemspot is empty. Two conditions that will always be true, when the prior has run.
Therefore I am taking the item out of the ItemSpot and putting it right back in.
I'll let this stand to remind myself ad anyone who might come across it, to always check (and post) the full code
Thank you and good night
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Losing object reference 2 Answers
"Object reference not set to an instance of an object" problem 1 Answer
Semi Generic With References 0 Answers