Why is SetParent not working?

I have a system where the player drags an object, then when they stop dragging the object, if the object is within a certain distance of a position, it is supposed to set its parent object to the object at that position.

Here is a snippet of the code I am using:

public void OnEndDrag(PointerEventData eventData)
{
	//checks if object is within 105 units of the position
	if (105 >= Mathf.Abs(eventData.position.x - pos[0].x) && 105 >= Mathf.Abs(eventData.position.y - pos[0].y))
	{
		//retrieves the corresponding object from the list for the current position
		if (GameObject.Find("LevelUpMenu").GetComponent<LevelUpMenu>().parentPos[0].transform.childCount == 3)
		{
			//fails to set the previously retrieved object as the new parent	
			transform.SetParent(GameObject.Find("LevelUpMenu").GetComponent<LevelUpMenu>().parentPos[0].transform, false);
			transform.position = transform.parent.position;
		}
	}
//basically the same stuff repeated for each position, followed by an "else move back to original position"
}

Can someone please tell me why SetParent isn’t working?

Have you verified that the code reaches the SetParent call and that GameObject.Find returns non-null?

@dstears I am fairly confident that it reaches the SetParent call, and that it does not return null, as the first section works, stopping the object if it is within the correct area, and the LevelUpMenu object has to be active in order to have this script run, and the corresponding object in the array is not null.

1 Answer

1

You’re checking if the object is more than 105 units away from the position, not less then. So that’s probably it.

No, I'm checking if 105 is greater than the distance, which is the same as checking if the distance is less than 105.