如果在Scene视图中可见,Game视图中不可见,大概率是因为Z值小于0,代码中将Z值设置为大于0即可;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwimCtroller : MonoBehaviour
{
public GameObject playerPrefab; // 预制体,用于创建新的线条
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0)) {
CreatePlayer();
}
}
private void CreatePlayer()
{
// 鼠标点击一个位置,生成一个player
// 获取鼠标点击的屏幕坐标
Vector3 mousePosition = Input.mousePosition;
// 随机生成一个大于0的float值;设置一个合适的z值,为了确保对象位于摄像机可以看到的范围内
mousePosition.z = UnityEngine.Random.Range(0.1f, 10.0f);
// 实例化player
GameObject player = Instantiate(playerPrefab);
player.transform.position = Camera.main.ScreenToWorldPoint(mousePosition);
}
}