Home > Blockchain >  Unity Transform not updating position realtime
Unity Transform not updating position realtime

Time:07-21

I am trying to create a simple scriptable object for my shoot ability. I have that aspect working, but as I try to set my Transform to my player, it does not update the shoot position. I am very new to C#, and this script isnt complete. I still need to add the functionality to destroy the created objects. Any help would be greatly appreciated. I suspect I need to add an update function but im am not certain how to do this.

    using UnityEngine.InputSystem;
using UnityEngine.AI;
using UnityEngine;
namespace EO.ARPGInput
{
[CreateAssetMenu]
public class Shoot : Ability
{

   public Transform projectileSpawnPoint;
   public GameObject projectilePrefab;
   public float bulletSpeed = 10;
   public float bulletLife = 3;

   
    public override void Activate(GameObject parent)
    {
        var projectile = Instantiate(projectilePrefab, projectileSpawnPoint.position, projectileSpawnPoint.rotation);
        projectile.GetComponent<Rigidbody>().velocity = projectileSpawnPoint.forward * bulletSpeed;
        Destroy(projectile, bulletLife);
        
        void OnCollisionEnter(Collision collision)
    {
        Destroy(projectile);
        
    }
   
    }

   
}
}

CodePudding user response:

I'm still new to Unity and coding also, so take my advice with a load of salt :P. It may be best to have a transform on your character (say just past the barrel of the player's gun) that you can put as the projectileSpawnPoint. In your code the projectileSpawnPoint is never set. Your first line of code in the "Activate" method should be something like:

public override void Activate(GameObject parent)
{

    projectileSpawnPoint = playerGunBarrelTransform.transform.position;

    var projectile = Instantiate(projectilePrefab, projectileSpawnPoint.position, projectileSpawnPoint.rotation);
    projectile.GetComponent<Rigidbody>().velocity = projectileSpawnPoint.forward * bulletSpeed;
    Destroy(projectile, bulletLife);

For destroying the projectile afterward you can keep it as you have it in OnCollision. howeer, with bullets in particular, since they tend to be instantiated A LOT and then destroyed afterward it would be best to use an object pooler for them to instantiate several of them on start and then disable and enable them as needed so you can resuse them instead of making new ones every time.

CodePudding user response:

you have to create a new script that derives from Monobehaviour for your projectiles. attach that script to the projectile prefab and place the OnCollisionEnter method in that script. now your projectiles should get destroyed when touching another collider. make sure that there is a rigidbody component attached to the projectile.

  • Related