脚本代码似乎仅适用于 prefb 的单个实例



我遇到了最奇怪的问题 我有一个光线投射,当它接触到某个层时,它会调用我的函数来执行一个小动画。

问题是,这仅适用于单个对象,我尝试复制,复制预制件,将预制件拖到场景中,但它不起作用。

现在我在下面有这段代码,正如你所看到的,我有这一行,它允许我访问public PlatformFall platfall;上的脚本,这样我就可以调用platfall.startFall();

我注意到,如果我将单个项目从层次结构拖到检查器中的公共 PlatFall,那么该 SINGLE 对象将正常工作。(因为它在调用 startFall 时会进行动画处理(。但是,如果我将预制件从我的项目拖到检查器,那么它们就不起作用。(即使调试日志显示该方法称为动画也不会发生(。

public class CharacterController2D : MonoBehaviour {
//JummpRay Cast
public PlatformFall platfall;
// LayerMask to determine what is considered ground for the player
public LayerMask whatIsGround;
public LayerMask WhatIsFallingPlatform;
// Transform just below feet for checking if player is grounded
public Transform groundCheck;
/*....
...*/
Update(){
//    Ray Casting to Fallingplatform
isFallingPlatform = Physics2D.Linecast(_transform.position, groundCheck.position, WhatIsFallingPlatform);
if (isFallingPlatform)
{
Debug.Log("Here");
platfall.startFall();
}
Debug.Log(isFallingPlatform);
}
}

平台脚本

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

public class PlatformFall : MonoBehaviour
{
public float fallDelay = 0.5f;
Animator anim;
Rigidbody2D rb2d;
void Awake()
{
Debug.Log("Awake Called");
anim = GetComponent<Animator>();
rb2d = GetComponent<Rigidbody2D>();
}
private void Start()
{
Debug.Log("Start Called");
}
//void OnCollisionEnter2D(Collision2D other)
//{
//    Debug.Log(other.gameObject.tag);
//    GameObject childObject = other.collider.gameObject;
//    Debug.Log(childObject);
//    if (other.gameObject.CompareTag("Feet"))
//    {
//        anim.SetTrigger("PlatformShake");
//        Invoke("Fall", fallDelay);
//        destroy the Log
//        DestroyObject(this.gameObject, 4);
//    }
//}
public void startFall()
{

anim.SetTrigger("PlatformShake");

Invoke("Fall", fallDelay);
Debug.Log("Fall Invoked");
// destroy the Log
//       DestroyObject(this.gameObject, 4);
}
void Fall()
{
rb2d.isKinematic = false;
rb2d.mass = 15;
}
}

我从您的帖子中了解到,您总是在调用检查器分配的 PlatformFall 实例。我认为此更改将解决您的问题。

public class CharacterController2D : MonoBehaviour {
private PlatformFall platfall;
private RaycastHit2D isFallingPlatform;
void FixedUpdate(){
isFallingPlatform = Physics2D.Linecast(_transform.position, groundCheck.position, WhatIsFallingPlatform);
if (isFallingPlatform)
{
Debug.Log("Here");
platfall = isFallingPlatform.transform.GetComponent<PlatformFall>();
platfall.startFall();
}
}
}

顺便说一下,我假设您将预制件放在适当的位置进行铸造。还有一件事,你应该在FixedUpdate中进行物理操作,这会影响你的刚体。

最新更新