c# - 如何在 Unity 中重生对象?

标签 c# unity3d spawn

我正在联合开发 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);       
    }

}

最佳答案

要生成一个球,您应该创建一个预制件并将其实例化。示例:

private class Spawner : MonoBehaviour
{
    public GameObject prefab;

    public GameObject Spawn() => Instantiate(prefab);
}

这样你的 throw 代码应该产生一个球,如果你想摧毁一个旧的球。

关于c# - 如何在 Unity 中重生对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59343202/

相关文章:

node.js - 防止通过 child_process.spawn 转发环境变量

node.js - 如何杀死在 nightwatch globals.js 中 : function in the after:function 之前产生的进程

c# - 无法将带 [] 的索引应用于 'Array' 类型的表达式 '

c# - 从数据集复制到 C# 中的 Access 表?

github - 如何从 Github 获取项目到 Unity

unity3d - Unity-我似乎无法保持我的游戏对象颜色

node.js - 如何模拟 Node.js child_process spawn 函数?

c# - 我应该为域和 EF 使用单独的模型吗?

c# - 如何覆盖 Razor 的 "name"HtmlAttribute

c# - 从 Unity 打开 iOS 应用程序