2017-08-13 149 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