2017-08-13 148 views
0

我遇到了最奇怪的问题 我有一个光线投射,当它触及某个图层时,它会调用我的函数来执行一个小动画。脚本代码似乎只适用于prefb的单个实例

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

现在我有这个代码的下方,你可以看到我有这行,让我访问public PlatformFall platfall;脚本,以便我可以调用platfall.startFall();

事情我已经注意到了,如果我拖动单个项目从层次结构到Inspector中的公共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; 
    } 
} 

回答

1

我从您的文章,你总是呼吁从督察分配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中进行影响刚体的物理操作。

+0

完美地工作,我的错误是什么?因为我在固定更新中没有这样做? –

+0

nope,你的代码调用相同的从检查器分配的PlatformFall实例。现在,它使用hitted对象的PlatformFall组件。 – OsmanSenol