简体   繁体   中英

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. 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. 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.

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.

Code with 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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