To achieve your requirements of being able to set different images and stopping points for each enemy from the Inspector, you can modify your dissolvenzaImmagini script to use a custom serializable class for each enemy sequence. This will allow you to group all the configurations for each enemy in one place and make it editable from the Inspector.
Below are the steps to modify your scripts accordingly:
1. Create a Serializable Class for Enemy Sequences
First, create a [System.Serializable] class that will hold all the configurations for each enemy. This class will include the enemy prefab, spawn point, images, target point, and stopping distance.
[System.Serializable]
public class EnemySequence
{
public GameObject enemyPrefab; // Prefab of the enemy
public Transform spawnPoint; // Spawn point for the enemy
public GameObject[] imagesBeforeSpawn; // Images to fade in before spawning the enemy
public GameObject[] imagesOnEnemyReach; // Images to fade in when the enemy reaches the target point
public GameObject[] imagesAfterEnemyDeath; // Images to fade in after the enemy is defeated
public Transform targetPoint; // The designated point the enemy should move to
public float stopDistance = 2.0f; // The stopping distance when the enemy reaches the target point
}
2. Modify the dissolvenzaImmagini Script
Update your dissolvenzaImmagini script to use the EnemySequence class. You will replace your individual arrays with a single array of EnemySequence, which will be easier to manage from the Inspector.
Update the Class Definition
Replace your existing arrays with the enemySequences array:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class dissolvenzaImmagini : MonoBehaviour
{
[Header("Sequence Settings")]
public GameObject[] initialImages; // Images to show at the beginning
public EnemySequence[] enemySequences; // Array of enemy sequences
public GameObject[] finalImages; // Images to fade in after all enemies are defeated
[Header("Fade Settings")]
public float fadeDuration = 3f; // Duration of the fade
public float displayDuration = 2f; // Duration to display the images
[Header("Player and Enemy Settings")]
public controller playerMovement; // Reference to player movement script
public Player_combat_Mattina combat; // Reference to player combat script
public enemySpawner[] enemySpawners; // References to enemy spawners
private int currentSequenceIndex = 0; // Index to track the current enemy sequence
private GameObject currentEnemy; // Reference to the current enemy
}
Initialize the Images
Update the Start() method to initialize the images for each enemy sequence:
void Start()
{
// Initialize images by setting their alpha to 0
SetGroupAlpha(initialImages, 0f);
SetGroupAlpha(finalImages, 0f);
// Initialize images in each enemy sequence
foreach (var sequence in enemySequences)
{
SetGroupAlpha(sequence.imagesBeforeSpawn, 0f);
SetGroupAlpha(sequence.imagesOnEnemyReach, 0f);
SetGroupAlpha(sequence.imagesAfterEnemyDeath, 0f);
}
DisablePlayerAndEnemies();
StartCoroutine(RunSequences());
}
Update the RunSequences Coroutine
Modify the RunSequences() coroutine to loop through the enemySequences array:
IEnumerator RunSequences()
{
// Fade in initial images if any
if (initialImages.Length > 0)
{
yield return StartCoroutine(FadeInGroup(initialImages));
yield return new WaitForSeconds(displayDuration);
yield return StartCoroutine(FadeOutGroup(initialImages));
}
// Loop through each enemy sequence
while (currentSequenceIndex < enemySequences.Length)
{
EnemySequence sequence = enemySequences[currentSequenceIndex];
// Fade in images before spawning enemy
if (sequence.imagesBeforeSpawn != null && sequence.imagesBeforeSpawn.Length > 0)
{
yield return StartCoroutine(FadeInGroup(sequence.imagesBeforeSpawn));
yield return new WaitForSeconds(displayDuration);
yield return StartCoroutine(FadeOutGroup(sequence.imagesBeforeSpawn));
}
// Spawn the enemy and wait for it to be defeated
yield return StartCoroutine(SpawnAndHandleEnemy(sequence));
// Fade in images after enemy death
if (sequence.imagesAfterEnemyDeath != null && sequence.imagesAfterEnemyDeath.Length > 0)
{
yield return StartCoroutine(FadeInGroup(sequence.imagesAfterEnemyDeath));
yield return new WaitForSeconds(displayDuration);
yield return StartCoroutine(FadeOutGroup(sequence.imagesAfterEnemyDeath));
}
currentSequenceIndex++;
}
// Fade in final images after all enemies are defeated
if (finalImages.Length > 0)
{
yield return StartCoroutine(FadeInGroup(finalImages));
yield return new WaitForSeconds(displayDuration);
yield return StartCoroutine(FadeOutGroup(finalImages));
}
// Re-enable player and enemies
EnablePlayerAndEnemies();
}
Update the SpawnAndHandleEnemy Method
Modify the SpawnAndHandleEnemy() method to use the EnemySequence parameter:
IEnumerator SpawnAndHandleEnemy(EnemySequence sequence)
{
// Spawn the enemy
currentEnemy = Instantiate(
sequence.enemyPrefab,
sequence.spawnPoint.position,
Quaternion.identity);
// Set up the enemy's movement and target
EnemyMovement movement = currentEnemy.GetComponent<EnemyMovement>();
if (movement == null)
{
movement = currentEnemy.AddComponent<EnemyMovement>();
}
movement.target = sequence.targetPoint != null ? sequence.targetPoint : transform; // Use sequence target or default to this object's transform
movement.stopDistance = sequence.stopDistance;
// Subscribe to the enemy reaching the target point
movement.OnReachTarget += () =>
{
StartCoroutine(HandleEnemyReachedTarget(sequence));
};
// Wait until the enemy is destroyed
Health enemyHealth = currentEnemy.GetComponent<Health>();
while (enemyHealth != null && enemyHealth.IsAlive())
{
yield return null;
}
}
Handle Enemy Reaching the Target
Create a method to handle the enemy reaching the target point:
IEnumerator HandleEnemyReachedTarget(EnemySequence sequence)
{
if (sequence.imagesOnEnemyReach != null && sequence.imagesOnEnemyReach.Length > 0)
{
yield return StartCoroutine(FadeInGroup(sequence.imagesOnEnemyReach));
yield return new WaitForSeconds(displayDuration);
yield return StartCoroutine(FadeOutGroup(sequence.imagesOnEnemyReach));
}
}
3. Update the EnemyMovement Script
Ensure that the EnemyMovement class can accept a custom target and stop distance for each enemy.
Modify the Start Method
Remove the check for a null target in the Start method to allow setting the target later:
protected virtual void Start()
{
// Get the NavMeshAgent component
agent = GetComponent<NavMeshAgent>();
if (agent == null)
{
Debug.LogError("NavMeshAgent missing on Enemy.");
enabled = false;
return;
}
// Get the SpriteRenderer component
spriteRenderer = GetComponent<SpriteRenderer>();
if (spriteRenderer == null)
{
Debug.LogWarning("SpriteRenderer missing on Enemy.");
// It's optional; some enemies may not have sprites
}
// Get the Animator component if not assigned
if (animator == null)
{
animator = GetComponent<Animator>();
}
// Target can be assigned later
}
Update the Update Method
Ensure that the enemy does not attempt to move if the target is not set:
protected virtual void Update()
{
if (target == null) return;
float distance = Vector3.Distance(transform.position, target.position);
if (distance <= chaseRange)
{
ChaseTarget();
FlipSprite();
// Check if reached the target
if (!hasReachedTarget && agent.remainingDistance <= stopDistance && !agent.pathPending)
{
hasReachedTarget = true; // Prevents multiple triggers
OnReachTarget?.Invoke();
}
}
else
{
// Stop the enemy if the target is out of range
agent.isStopped = true;
if (animator != null)
{
animator.SetBool("running", false);
}
}
}
4. Using the Inspector to Assign Values
With these changes, you can now assign different images and stopping points for each enemy directly from the Inspector.
Assigning Enemy Sequences
In the Inspector, you will see an array called Enemy Sequences. For each element in this array, you can expand and assign:
- Enemy Prefab: The prefab for the enemy.
- Spawn Point: Where the enemy will spawn.
- Images Before Spawn: Images to fade in before this enemy spawns.
- Images On Enemy Reach: Images to fade when this enemy reaches the target point.
- Images After Enemy Death: Images to fade in after this enemy is defeated.
- Target Point: The point the enemy should move towards (can be different from the player).
- Stop Distance: The distance from the target point at which the enemy stops moving.
Assigning Initial and Final Images
Similarly, assign any images you want to fade in at the beginning or end of the sequence using the Initial Images and Final Images arrays.
5. Additional Notes
- NavMesh Setup: Ensure that your scene has the NavMesh set up properly and that your enemies have the
NavMeshAgent component.
- Sprite Flip: If some of your enemies don't use sprites, you might want to handle the absence of a
SpriteRenderer gracefully.
- Default Values: If you don't assign a
Target Point in the EnemySequence, the enemy will use the transform of the dissolvenzaImmagini object as the default target.
6. Complete Updated Scripts
dissolvenzaImmagini.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
[System.Serializable]
public class EnemySequence
{
public GameObject enemyPrefab; // Prefab of the enemy
public Transform spawnPoint; // Spawn point for the enemy
public GameObject[] imagesBeforeSpawn; // Images to fade in before spawning the enemy
public GameObject[] imagesOnEnemyReach; // Images to fade in when the enemy reaches the target point
public GameObject[] imagesAfterEnemyDeath; // Images to fade in after the enemy is defeated
public Transform targetPoint; // The designated point the enemy should move to
public float stopDistance = 2.0f; // The stopping distance when the enemy reaches the target point
}
public class dissolvenzaImmagini : MonoBehaviour
{
[Header("Sequence Settings")]
public GameObject[] initialImages; // Images to show at the beginning
public EnemySequence[] enemySequences; // Array of enemy sequences
public GameObject[] finalImages; // Images to fade in after all enemies are defeated
[Header("Fade Settings")]
public float fadeDuration = 3f; // Duration of the fade
public float displayDuration = 2f; // Duration to display the images
[Header("Player and Enemy Settings")]
public controller playerMovement; // Reference to player movement script
public Player_combat_Mattina combat; // Reference to player combat script
public enemySpawner[] enemySpawners; // References to enemy spawners
private int currentSequenceIndex = 0; // Index to track the current enemy sequence
private GameObject currentEnemy; // Reference to the current enemy
void Start()
{
// Initialize images by setting their alpha to 0
SetGroupAlpha(initialImages, 0f);
SetGroupAlpha(finalImages, 0f);
// Initialize images in each enemy sequence
foreach (var sequence in enemySequences)
{
SetGroupAlpha(sequence.imagesBeforeSpawn, 0f);
SetGroupAlpha(sequence.imagesOnEnemyReach, 0f);
SetGroupAlpha(sequence.imagesAfterEnemyDeath, 0f);
}
DisablePlayerAndEnemies();
StartCoroutine(RunSequences());
}
void DisablePlayerAndEnemies()
{
if (playerMovement != null) playerMovement.enabled = false;
if (combat != null) combat.enabled = false;
foreach (enemySpawner spawner in enemySpawners)
{
if (spawner != null) spawner.enabled = false;
}
}
void EnablePlayerAndEnemies()
{
if (playerMovement != null) playerMovement.enabled = true;
if (combat != null) combat.enabled = true;
foreach (enemySpawner spawner in enemySpawners)
{
if (spawner != null) spawner.enabled = true;
}
}
IEnumerator RunSequences()
{
// Fade in initial images if any
if (initialImages.Length > 0)
{
yield return StartCoroutine(FadeInGroup(initialImages));
yield return new WaitForSeconds(displayDuration);
yield return StartCoroutine(FadeOutGroup(initialImages));
}
// Loop through each enemy sequence
while (currentSequenceIndex < enemySequences.Length)
{
EnemySequence sequence = enemySequences[currentSequenceIndex];
// Fade in images before spawning enemy
if (sequence.imagesBeforeSpawn != null && sequence.imagesBeforeSpawn.Length > 0)
{
yield return StartCoroutine(FadeInGroup(sequence.imagesBeforeSpawn));
yield return new WaitForSeconds(displayDuration);
yield return StartCoroutine(FadeOutGroup(sequence.imagesBeforeSpawn));
}
// Spawn the enemy and wait for it to be defeated
yield return StartCoroutine(SpawnAndHandleEnemy(sequence));
// Fade in images after enemy death
if (sequence.imagesAfterEnemyDeath != null && sequence.imagesAfterEnemyDeath.Length > 0)
{
yield return StartCoroutine(FadeInGroup(sequence.imagesAfterEnemyDeath));
yield return new WaitForSeconds(displayDuration);
yield return StartCoroutine(FadeOutGroup(sequence.imagesAfterEnemyDeath));
}
currentSequenceIndex++;
}
// Fade in final images after all enemies are defeated
if (finalImages.Length > 0)
{
yield return StartCoroutine(FadeInGroup(finalImages));
yield return new WaitForSeconds(displayDuration);
yield return StartCoroutine(FadeOutGroup(finalImages));
}
// Re-enable player and enemies
EnablePlayerAndEnemies();
}
IEnumerator SpawnAndHandleEnemy(EnemySequence sequence)
{
// Spawn the enemy
currentEnemy = Instantiate(
sequence.enemyPrefab,
sequence.spawnPoint.position,
Quaternion.identity);
// Set up the enemy's movement and target
EnemyMovement movement = currentEnemy.GetComponent<EnemyMovement>();
if (movement == null)
{
movement = currentEnemy.AddComponent<EnemyMovement>();
}
movement.target = sequence.targetPoint != null ? sequence.targetPoint : transform; // Use sequence target or default to this object's transform
movement.stopDistance = sequence.stopDistance;
// Subscribe to the enemy reaching the target point
movement.OnReachTarget += () =>
{
StartCoroutine(HandleEnemyReachedTarget(sequence));
};
// Wait until the enemy is destroyed
Health enemyHealth = currentEnemy.GetComponent<Health>();
while (enemyHealth != null && enemyHealth.IsAlive())
{
yield return null;
}
}
IEnumerator HandleEnemyReachedTarget(EnemySequence sequence)
{
if (sequence.imagesOnEnemyReach != null && sequence.imagesOnEnemyReach.Length > 0)
{
yield return StartCoroutine(FadeInGroup(sequence.imagesOnEnemyReach));
yield return new WaitForSeconds(displayDuration);
yield return StartCoroutine(FadeOutGroup(sequence.imagesOnEnemyReach));
}
}
IEnumerator FadeInGroup(GameObject[] group)
{
float elapsedTime = 0f;
while (elapsedTime < fadeDuration)
{
elapsedTime += Time.deltaTime;
SetGroupAlpha(group, Mathf.Clamp01(elapsedTime / fadeDuration));
yield return null;
}
SetGroupAlpha(group, 1f);
}
IEnumerator FadeOutGroup(GameObject[] group)
{
float elapsedTime = 0f;
while (elapsedTime < fadeDuration)
{
elapsedTime += Time.deltaTime;
SetGroupAlpha(group, Mathf.Clamp01(1f - (elapsedTime / fadeDuration)));
yield return null;
}
SetGroupAlpha(group, 0f);
}
void SetGroupAlpha(GameObject[] group, float alpha)
{
foreach (GameObject obj in group)
{
if (obj != null)
{
Image[] images = obj.GetComponentsInChildren<Image>();
foreach (Image img in images)
{
Color color = img.color;
color.a = alpha;
img.color = color;
}
}
}
}
}
EnemyMovement.cs
using UnityEngine;
using UnityEngine.AI;
using System;
public class EnemyMovement : MonoBehaviour
{
[Header("Target Settings")]
public Transform target; // Reference to the target Transform
public float stopDistance = 2.0f; // Distance at which the enemy stops moving towards the target
[Header("Animation Settings")]
public Animator animator; // Reference to the Animator
[Header("Movement Settings")]
public float chaseRange = 100f; // Set a large range or adjust as needed
public Action OnReachTarget; // Event to signal when the enemy reaches the target
private NavMeshAgent agent;
private SpriteRenderer spriteRenderer;
private bool hasReachedTarget = false; // Flag to ensure OnReachTarget is called only once
protected virtual void Start()
{
// Get the NavMeshAgent component
agent = GetComponent<NavMeshAgent>();
if (agent == null)
{
Debug.LogError("NavMeshAgent missing on Enemy.");
enabled = false;
return;
}
// Get the SpriteRenderer component
spriteRenderer = GetComponent<SpriteRenderer>();
if (spriteRenderer == null)
{
// It's optional; some enemies may not have sprites
}
// Get the Animator component if not assigned
if (animator == null)
{
animator = GetComponent<Animator>();
}
// Target can be assigned later
}
protected virtual void Update()
{
if (target == null) return;
float distance = Vector3.Distance(transform.position, target.position);
if (distance <= chaseRange)
{
ChaseTarget();
FlipSprite();
// Check if reached the target
if (!hasReachedTarget && agent.remainingDistance <= stopDistance && !agent.pathPending)
{
hasReachedTarget = true; // Prevents multiple triggers
agent.isStopped = true;
if (animator != null)
{
animator.SetBool("running", false);
}
OnReachTarget?.Invoke();
}
}
else
{
// Stop the enemy if the target is out of range
agent.isStopped = true;
if (animator != null)
{
animator.SetBool("running", false);
}
}
}
protected void ChaseTarget()
{
if (agent != null && target != null)
{
agent.isStopped = false;
agent.SetDestination(target.position);
if (animator != null)
{
animator.SetBool("running", true);
}
}
}
protected void FlipSprite()
{
if (spriteRenderer == null) return;
Vector3 direction = agent.desiredVelocity;
if (direction.x != 0)
{
spriteRenderer.flipX = direction.x < 0;
}
}
}
Conclusion
By restructuring your scripts to use the EnemySequence class, you gain the flexibility to assign different images and stopping points for each enemy directly from the Inspector. This approach makes your sequences more manageable and customizable, aligning with your requirements.
If you have any questions or need further assistance, feel free to ask!