如何在C#中将胶囊碰撞器的物理材质更改为true或false作为布尔值?

huangapple go评论84阅读模式
英文:

Unity & C# // How can I change the physical material of the capsule collider to true or false as a Bool value in C#?

问题

我正在使用Unity制作一个小游戏,但我遇到了一个小问题,你能帮我吗?

如何在C#中将胶囊碰撞器的物理材质更改为true或false作为布尔值?

我已经创建了一个物理材质并将其应用于我的玩家的胶囊碰撞器。在C#中,我想通过布尔值手动设置为true或false。

英文:

I'm making a small game with Unity, but I'm having a small problem, can you help me?

How can I change the physical material of the capsule collider to true or false as a Bool value in C#?

I've created a physics material and applied it to my Player's Capsule Collider. In C#, I want to manually set true or false value through bool.

答案1

得分: 0

[SerializeField] PhysicMaterial materialToApply;
[SerializeField] CapsuleCollider colliderToAdjust;

void TogglePhysicsMaterial(bool Toggle)
{
if (Toggle)
{
colliderToAdjust.material = materialToApply;
}
else
{
colliderToAdjust.material = null;
}
}

As others have said, just set the material property to null when you don't want it, and assign it when you do. I saw you want to have it toggle on jump, so here is a quick and dirty way as an example:

void Update()
{
if(colliderToAdjust.transform.position.y > 0
&& !colliderToAdjust.material)
{
TogglePhysicsMaterial(true);
}
else if(colliderToAdjust.transform.position.y <= 0
&& colliderToAdjust.material)
{
TogglePhysicsMaterial(false);
}
}

There are plenty of (MUCH) better ways to handle jump detection (e.g. Raycasts) so please don't think this is a good method as it relies on the capsule being placed at 0 height and wouldn't work with an incline.

英文:
[SerializeField] PhysicMaterial materialToApply;
[SerializeField] CapsuleCollider colliderToAdjust;

void TogglePhysicsMaterial(bool Toggle)
{
    if (Toggle)
    {
        colliderToAdjust.material = materialToApply;
    }
    else
    {
        colliderToAdjust.material = null;
    }
}

As others have said, just set the material property to null when you don't want it, and assign it when you do. I saw you want to have it toggle on jump, so here is a quick and dirty way as an example:

void Update()
{
    if(colliderToAdjust.transform.position.y &gt; 0
        &amp;&amp; !colliderToAdjust.material)
    {
        TogglePhysicsMaterial(true);
    }
    else if(colliderToAdjust.transform.position.y &lt;= 0
        &amp;&amp; colliderToAdjust.material)
    {
        TogglePhysicsMaterial(false);
    }
}

There are plenty of (MUCH) better ways to handle jump detection (e.g. Raycasts) so please don't think this is a good method as it relies on the capsule being placed at 0 height and wouldn't work with an incline.

huangapple
  • 本文由 发表于 2023年7月31日 20:33:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76803677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定