private void OnCollisionEnter2D(Collision2D collision)
{
while (onWeapon == false && collision.gameObject.tag == "Weapon")
{
onWeapon = true;
}
if (onWeapon == true && Input.GetKey(KeyCode.E))
{
currentPos = gameObject.transform.position;
collision.transform.position = currentPos;
collision.transform.parent = player.transform;
collision.tag = "WeaponHeld";
}
}
i cant change the object tag on runtime with "OnEnterCollision2D" but the same line worked when i used "OnTriggerEnter2D"
First of all what is your while
loop good for? Anyway there will be only exactly one single iteration so just make it
if(!onWeapon && collision.gameObject.CompareTag("Weapon"))
{
onWeapon = true;
}
Then aCollision2D
is a data container struct with specific data about the collision and itself has no tag.
The gameObject
you collide with has
collision.gameObject.tag = "WeaponHeld";
Or since you are using the transform
anyway you can also use that one
var otherTransform = collision.transform;
otherTransform.position = currentPos;
otherTransform.parent = player.transform;
otherTransform.tag = "WeaponHeld";
because it has the property tag
as well which forwards to the according gameObject.tag
.
Why did it work in
OnTriggerEnter2D
?
Because there as a parameter you don't get aCollision2D
struct but rather a Collider2D
component reference.
And as just mentioned also for Transform
the base class Component
has the property tag
which basically simply forwards to the according gameObject.tag
(see source code ).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.