如何在Unity中重新生成对象?

问题描述 投票:2回答:2

我正在统一进行3D篮球比赛。

它有一个分数和一个计时器。一段时间后,我的场景将加载并从头开始。每次扔球时,都必须产生它。

它有一个生成按钮和一个拍摄按钮。但是我不想使用生成按钮。所以我想自动产生球。

我该怎么办?我在下面给出我的生成按钮代码和抛出按钮代码。

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

public class SpawnButton: MonoBehaviour
{

    public GameObject ball;
    public GameObject BallPosition;

    public void Spawn()
    {
        ball.transform.position = BallPosition.transform.position;
        var ballPosition = ball.transform.position;
        ball.GetComponent<Rigidbody>().useGravity = false;
        ball.GetComponent<Rigidbody>().velocity = Vector3.zero;
        ball.transform.position = ballPosition;
    }

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

public class ThrowButton: MonoBehaviour
{
    static Animator anim;
    public GameObject ball;
    public float ballThrowingForce = 5f;
    internal bool holdingBall;


    void Start()
    {
        anim = GetComponent<Animator>();
        ball.GetComponent<Rigidbody>().useGravity = false;
    }


    public void Throw()
    {
        anim.SetTrigger("isThrowing");
        StartCoroutine(Test());        
    }

    IEnumerator Test()
    {
        yield return new WaitForSeconds(1.5f);
        ball.GetComponent<Rigidbody>().useGravity = true;
        //ball.GetComponent<Rigidbody>().AddForce(transform.up * ballThrowingForce);
        ball.GetComponent<Rigidbody>().AddForce(0, 380.0f, ballThrowingForce);       
    }

}
c# unity3d spawn
2个回答
1
投票
private class Spawner : MonoBehaviour { public GameObject prefab; public GameObject Spawn() => Instantiate(prefab); }

因此,您的投掷代码应产生一个球,如果您想销毁一个旧的球。


0
投票
可以的]

    使用Invoke(“ SpawnNewBallMethod”,3)///在执行这段代码之后,它等待3秒钟并执行您在其中提到的方法,该方法可以实例化代码。
  1. 或者在完成第一个球的工作后,您可以销毁它(销毁(球))或将active设置为false-然后检查状态(是否存在(是否为空检查?)或gameObject.active == true)并因此实例化一个新的球(如果它是setactive(false),请不要忘记稍后销毁它)。

  2. 尽管gameObject.active已过时,但它将达到目的而不会使事情复杂化。我认为Invoke比IEnumerator好,因为Invoke不会在计时器运行时停止执行流并继续执行其他操作。
© www.soinside.com 2019 - 2024. All rights reserved.