Pierce Jennings
Pierce Jennings

Reputation: 65

Sprite doesn't show up after telling it to move

In my most recent code update the sprite doesn't want to show anymore before I could pull the prefab into the hierarchy and it would show and it will still do that. But whenever I spawn it in with code the image doesn't show. The update I did spawns the sprites and then moves them down a path. I can see the sprite move in the inspector but can't see it on screen.

MoveEnemy script

public class MoveEnemy : MonoBehaviour
{

    [HideInInspector]
    public GameObject[] waypoints;
    private int currentWaypoint = 0;
    private float lastWaypointSwitchTime;
    public float speed = 1.0f;

    // Start is called before the first frame update
    void Start()
    {
        lastWaypointSwitchTime = Time.time;
    }

    // Update is called once per frame
    void Update()
    {
        // 1
        Vector3 startPosition = waypoints
        [currentWaypoint].transform.position;
        Vector3 endPosition = waypoints[currentWaypoint + 1].transform.position;

        // 2
        float pathLength = Vector3.Distance(startPosition, endPosition);
        float totalTimeForPath = pathLength / speed;
        float currentTimeOnPath = Time.time - lastWaypointSwitchTime;
        gameObject.transform.position = Vector2.Lerp(startPosition, endPosition, currentTimeOnPath / totalTimeForPath);

        // 3
        if (gameObject.transform.position.Equals(endPosition))
        {
            if (currentWaypoint < waypoints.Length - 2)
            {
                // 3.a
                currentWaypoint++;
                lastWaypointSwitchTime = Time.time;
                // TODO: Rotate into move direction
            }
            else
            {
                // 3.b
                Destroy(gameObject);

                AudioSource audioSource = gameObject.GetComponent<AudioSource>();
                AudioSource.PlayClipAtPoint(audioSource.clip, transform.position);
                // TODO: deduct health
            }
        }
    }
}

// Credit raywenderlich.com

SpawnEnemy script

public class SpawnEnemy : MonoBehaviour
{

    public GameObject[] waypoints;
    public GameObject testEnemyPrefab;

    // Start is called before the first frame update
    void Start()
    {
        Instantiate(testEnemyPrefab).GetComponent<MoveEnemy>().waypoints = waypoints;
    }

Upvotes: 1

Views: 49

Answers (2)

Pierce Jennings
Pierce Jennings

Reputation: 65

Whenever I changed the camera render mode the screen space moved but the sprite didn't so I just had to move it back into the screen space.

Upvotes: 1

Ege
Ege

Reputation: 51

I think objects spawning behind the camera. Move the camera a bit back. Set the view to 3d world space. Then move the camera along z axis. Or change the spawnpoint's z axis.

Upvotes: 0

Related Questions