- Home /
Question by
nicktory · Sep 27, 2016 at 10:37 AM ·
networkinginstantiateplayerserverclient
Instantiated object from client player not moving when spawned. How can I fix this?
I've been trying to create a homing projectile which will home in on the player's current target similar to an rts, moba, or top down dungeon crawler. The problem I've been having is when the projectile is fired from the host player everything works fine but when the object is fired by the client the projectile's object is created but does not move. I've been trying to find solutions for a while but haven't had any luck. This code is the closest I've come to the intended effect.
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class attackScript : NetworkBehaviour {
public float attackRange = 10f;
public float attackSpeed = 2f;
public ClickToMove clickToMove;
public GameObject bulletPrefab;
public Transform Bullet;
void Start() {
ClickToMove clickToMove = GetComponent<ClickToMove>();
}
[Command]
public void CmdAttack()
{
GameObject bullet = (GameObject)Instantiate(bulletPrefab, Bullet.position, Bullet.rotation);
bullet.GetComponent<BulletScript>().Target = clickToMove.targetedEnemy;
NetworkServer.Spawn(bullet);
}
}
The target is received from this part of the ClickToMove script.
if (!isLocalPlayer)
{
return;
}
attackScript AttackScript = GetComponent<attackScript>();
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Input.GetButtonDown("Fire2")) {
if (Physics.Raycast(ray, out hit, 100)) {
if (hit.collider.CompareTag("Enemy"))
{ targetedEnemy = hit.transform;
currentTarget = hit.collider.gameObject;
enemyClick = true;
}
else { walking = true;
enemyClick = false;
navMeshAgent.destination = hit.point;
navMeshAgent.Resume();
}
}
}
And the projectile Bullet's script is
public class BulletScript : NetworkBehaviour
{
public float speed = 10f;
public Transform Target;
void Start()
{
}
void Update()
{
if (Target == null) return;
else
{
transform.LookAt(Target.transform.position);
transform.position = Vector3.MoveTowards(transform.position, Target.transform.position, Time.deltaTime * speed);
}
if (transform.position == Target.transform.position)
{
Destroy(gameObject);
}
}
}
I'm new to Networking, and Unity in general so any help is appreciated.
Comment