I made the script which moves chosen companion to the place behind Player at the start of the Scene. It works well when I start the game, but when I change Scene (moving character in gameplay) to another and then go back, Player character is in right place, but companion spaws in default place (Inspector values). I have no idea why is this happening…
Companion is on the Scene already as normal GameObject (not Static) and as I said it works after I hit play, but not after changing Scene and coming back.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class KompanFollow : MonoBehaviour {
System.Random losuj;
private CharacterController character_Controller;
public GameObject Player;
public Animator ani;
int timer = 0;
bool destination = false;
int IdleAni = 0;
public NavMeshAgent agent;
GameObject player;
bool ustawienie = false;
// Use this for initialization
void Awake()
{
character_Controller = GetComponent<CharacterController>();
}
public void Start () {
player = GameObject.Find("PlayerCharacter");
if (player.GetComponent<player>().Ilu_Towarzyszy() == 0)
{
Debug.Log("No companion");
this.gameObject.SetActive(false);
}
else if (this.gameObject.name == "Stefka" && player.GetComponent<player>().Kto_Towarzyszy() != 0)
{
Debug.Log("No Stefka (companion 0)");
this.gameObject.SetActive(false);
}
else if (this.gameObject.name == "Saifer" && player.GetComponent<player>().Kto_Towarzyszy() != 1)
{
Debug.Log("No Saifer (companion 1)");
this.gameObject.SetActive(false);
}
if (this.gameObject.activeSelf)
{
ani = GetComponent<Animator>();
losuj = player.GetComponent<PowerOfCreation>().radek;
IdleAni = losuj.Next(1, 22);
//set companion behind Player
gameObject.transform.position = new Vector3(player.GetComponent<PowerOfCreation>().positionplayera[0], player.GetComponent<PowerOfCreation>().positionplayera[3], player.GetComponent<PowerOfCreation>().positionplayera[1]);
gameObject.transform.eulerAngles = new Vector3(gameObject.transform.eulerAngles.x, player.GetComponent<PowerOfCreation>().positionplayera[2], gameObject.transform.eulerAngles.z);
gameObject.transform.position -= (2 * gameObject.transform.forward);
//player.GetComponent<PowerOfCreation>().positionplayera[0/1/2] is changed on one Scene (before transition to another) and Player character is set in Start function acording to those 3 values, so Player charcater appears on new map in the right place (not same as Inspector position) (and it works!)
}
}
// Update is called once per frame
void Update()
{
if (timer <= 12)
timer++;
else
{
timer = 0;
}
if (((Player.transform.position) - transform.position).sqrMagnitude > 13)
{
if (timer == 12)
{
agent.SetDestination(Player.transform.position);
destination = true;
}
if (destination)
{
agent.isStopped = false;
ani.Play("RUN");
}
}
else
{
agent.ResetPath();
agent.isStopped = true;
destination = false;
ani.Play("IDLE" + IdleAni);
}
}
}