Question by
Tilcob · Jun 27, 2020 at 05:50 PM ·
instantiate2d gamebuy
My instantiate clones won't behave like the original Prefab
When I spawning my clone it behaves not a bit like my prefab in the scene Code Turrent:
public class Turrent : MonoBehaviour { [Header("Attributes")]
public float range = 10f;
public float fireRate = 1f;
private float fireCountdown = 0f;
[Header("Unity Setup Fields")]
public string enemyTag = "Enemy";
public Transform rotateCanon;
public float turnSpeed = 20;
private Transform target;
public GameObject bulletPrefab;
public Transform firePoint;
void Start()
{
InvokeRepeating("UpdateTarget", 0f, 0.2f);
}
void Update()
{
if(target == null)
{
rotateCanon.rotation = Quaternion.Euler(0f, 0f, 180f);
return;
}
Vector3 dir = -target.position + transform.position;
Quaternion lookRotaion = Quaternion.LookRotation(dir);
Vector3 rotation = Quaternion.Lerp(rotateCanon.rotation, lookRotaion, turnSpeed * Time.deltaTime).eulerAngles;
rotateCanon.rotation = Quaternion.Euler(0f, 0f, rotation.z);
if(fireCountdown <= 0f)
{
Shoot();
fireCountdown = 1f / fireRate;
}
fireCountdown -= Time.deltaTime;
}
void Shoot()
{
GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Bullet bullet = bulletGO.GetComponent<Bullet>();
if(bullet != null)
{
bullet.Seek(target);
}
}
void UpdateTarget()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag(enemyTag);
float shortestDistance = Mathf.Infinity;
GameObject nearestEnemy = null;
foreach (GameObject enemy in enemies)
{
float distanceToEnemy = Vector2.Distance(transform.position, enemy.transform.position);
if(distanceToEnemy < shortestDistance)
{
shortestDistance = distanceToEnemy;
nearestEnemy = enemy;
}
}
if(nearestEnemy != null && shortestDistance <= range)
{
target = nearestEnemy.transform;
}
else
{
target = null;
}
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.black;
Gizmos.DrawWireSphere(transform.position, range);
}
}
Code Buying:
public class BulletCanonIsOn : MonoBehaviour { public GameObject canon; public GameObject spawnPoint; public GameObject buildingField;
public void setActive()
{
GameObject canonInst = (GameObject)Instantiate(canon, spawnPoint.transform.position, canon.transform.rotation);
Turrent canonTur = canonInst.GetComponent<Turrent>();
buildingField.SetActive(false);
}
}
Comment
Your answer
Follow this Question
Related Questions
Want to instantiate Prefab in its parent. 1 Answer
Addforce function not adding force in a 2D game and cannot figure out why 2 Answers
How to prevent a 2D sprite from being instantiated so it overlaps another 2D sprite. 0 Answers
How to instantiate various prefabs above a sprite and center them. 0 Answers
Duplicating and Instantiating a UI Image next to the previous. 0 Answers