Hi Grey,
Thanks a lot for your help, it is my own fault that I did not past the whole script.
It turns out that the FindGameObjectWithTag(“Player”) does work if the game object is destroyed, but I had that bit of the code at the end of the update section, which means it was not ever running because at the top of the update there is the line “if (currentBallRigidbody == null) { return; }”.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class BallHandler : MonoBehaviour
{
[SerializeField] GameObject ballprefab;
[SerializeField] Rigidbody2D pivot;
[SerializeField] float detatchDelay;
[SerializeField] float respawnDelay;
Rigidbody2D currentBallRigidbody;
SpringJoint2D currentBallSpringJoint;
public GameObject player;
private Camera mainCamera;
private bool isDragging;
void Start()
{
SpawnNewBall();
mainCamera = Camera.main;
}
void Update()
{
if (currentBallRigidbody == null) { return; }
if(!Touchscreen.current.primaryTouch.press.isPressed)
{
if (isDragging)
{
LaunchBall();
}
isDragging = false;
return;
}
isDragging = true;
currentBallRigidbody.isKinematic = true;
Vector2 touchPosition = Touchscreen.current.primaryTouch.position.ReadValue();
Vector3 worldPosition = mainCamera.ScreenToWorldPoint(touchPosition);
currentBallRigidbody.position = worldPosition;
currentBallRigidbody.isKinematic = true;
if (GameObject.FindGameObjectWithTag("Player") == null)
{
Invoke(nameof(SpawnNewBall), respawnDelay);
Debug.Log("spawning new ball");
}
}
private void LaunchBall()
{
currentBallRigidbody.isKinematic = false;
currentBallRigidbody = null;
Invoke(nameof(DetatchBall), detatchDelay);
}
private void DetatchBall()
{
currentBallSpringJoint.enabled = false;
currentBallSpringJoint = null;
}
private void SpawnNewBall()
{
GameObject ballInstance = Instantiate(ballprefab, pivot.position, Quaternion.identity);
currentBallRigidbody = ballInstance.GetComponent<Rigidbody2D>();
currentBallSpringJoint = ballInstance.GetComponent<SpringJoint2D>();
currentBallSpringJoint.connectedBody = pivot;
}
}
But I still couldn’t quite figure it out… I tried to put the
if (GameObject.FindGameObjectWithTag("Player") == null)
{
Invoke(nameof(SpawnNewBall), respawnDelay);
Debug.Log("spawning new ball");
}
at the top in the update, above the
if (currentBallRigidbody == null) { return; }
but then it keeps spawning unlimited balls after the first one is destroyed. Still not sure how to make it work to spawn just one new ball.