简体   繁体   English

新的统一,为什么这个脚本不移动 object? (统一 3D)

[英]New to unity, why does this script not move the object? (Unity 3D)

I am new to c# and unity, and I am trying to make a 3d game.我是 c# 和统一的新手,我正在尝试制作 3d 游戏。 This code is supposed to make a sword move back and forth, and when I press the button, unity acknowledges it, but the sword doesn't move.这段代码应该让剑来回移动,当我按下按钮时,unity会承认它,但剑不会移动。 Does anyone know why it's doing this?有谁知道它为什么这样做?

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

public class slash : MonoBehaviour
{
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        bool slas = false;
       if (Input.GetKeyDown(KeyCode.DownArrow))
        {
        slas = true;
        }
        if (slas = true)
        {
         transform.Rotate(0, 30, 0);
         transform.Rotate(0,-30,0);
        }

    } 
    
    
    
}

What you do right now in code is move your Sword 30 degress and than isntantly move it back 30 degrees.您现在在代码中所做的是将您的剑移动 30 度,而不是将其向后移动 30 度。

transform.Rotate(0, 30, 0);
transform.Rotate(0,-30,0);

And because it happens so fast you don't see it actually moving.而且因为它发生得如此之快,你看不到它实际上在移动。

What you need to do is add a Delay between these two actions to actually see it move.您需要做的是在这两个动作之间添加一个延迟以实际看到它移动。 You could either use Animations and then play that Animation in code or you just use an IEnumerator to delay the second action.您可以使用动画,然后在代码中播放 Animation,或者您只需使用 IEnumerator 来延迟第二个动作。

Code with IEnumerator:带有 IEnumerator 的代码:

float delay = 0.5f;

void Update() {
    if (Input.GetKeyDown(KeyCode.DownArrow)) {
        // Starting IEnumerator
        StartCoroutine(SwingSword());
    }
}

IEnumerator SwingSword() {
   // Swing forwards
   transform.Rotate(0, 30, 0);

   // Delay
   yield return new WaitForSeconds(delay);

   // Swing backwards
   transform.Rotate(0,-30,0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM