how to make PlayerController Script use Touch Input - c#

How do I make my PlayerController Script get touch input to make the player move in unity5? I tried changing the Input.GetKeyDown to GetMouseDown and GetTouch, but nothing happens when ever I click on the buttons, please help...thanks in advance.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
private static PlayerController instance;
public static PlayerController Instance
{
get
{
if(instance == null)
{
instance = GameObject.FindObjectOfType<PlayerController>();
}
return instance;
}
}
private Animator myAnimator;
[SerializeField]
private Transform bulletPosition;
[SerializeField]
private float movementSpeed;
private bool facingRight;
[SerializeField]
private Transform[] groundPoints;
[SerializeField]
private float groundRadius;
[SerializeField]
private LayerMask whatIsGround;
[SerializeField]
public bool airControl;
[SerializeField]
private float jumpForce;
[SerializeField]
private GameObject bulletPrefab;
public Rigidbody2D MyRigidbody{ get; set;}
public bool Attack{ get; set;}
public bool Jump{ get; set;}
public bool OnGround{ get; set;}
// Use this for initialization
void Start ()
{
facingRight = true;
MyRigidbody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
HandleInput();
}
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
Debug.Log(horizontal);
OnGround = IsGrounded();
HandleMovement(horizontal);
Flip(horizontal);
HandleLayers();
}
private void HandleMovement(float horizontal)
{
if (MyRigidbody.velocity.y < 0)
{
myAnimator.SetBool("land", true);
}
if (!Attack && (OnGround || airControl))
{
MyRigidbody.velocity = new Vector2(horizontal * movementSpeed, MyRigidbody.velocity.y);
}
if (Jump && MyRigidbody.velocity.y == 0)
{
MyRigidbody.AddForce(new Vector2(0, jumpForce));
}
myAnimator.SetFloat ("speed", Mathf.Abs (horizontal));
}
private void HandleInput()
{
if(Input.GetKeyDown(KeyCode.Space))
{
myAnimator.SetTrigger("jump");
}
if(Input.GetKeyDown(KeyCode.C))
{
myAnimator.SetTrigger("attack");
}
}
private void Flip(float horizontal)
{
if(horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
private bool IsGrounded()
{
if(MyRigidbody.velocity.y <= 0)
{
foreach(Transform point in groundPoints)
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(point.position, groundRadius, whatIsGround);
for(int i = 0; i <colliders.Length; i++)
{
if(colliders[i].gameObject != gameObject)
{
return true;
}
}
}
}
return false;
}
private void HandleLayers()
{
if(!OnGround)
{
myAnimator.SetLayerWeight(1, 1);
}
else
{
myAnimator.SetLayerWeight(1, 0);
}
}
public void ShootBullet(int value)
{
if(!OnGround && value == 1 || OnGround && value == 0)
{
if (facingRight)
{
GameObject tmp = (GameObject)Instantiate(bulletPrefab, bulletPosition.position, Quaternion.Euler(new Vector3(0, 0, 0)));
tmp.GetComponent<Bullet>().Initialize(Vector2.right);
}
else
{
GameObject tmp = (GameObject)Instantiate(bulletPrefab, bulletPosition.position, Quaternion.Euler(new Vector3(0, 0, 180)));
tmp.GetComponent<Bullet>().Initialize(Vector2.left);
}
}
}
}

Related

How to pause the object from moving if the travelTime variable value is empty in the editor in the inspector?

when i set the travelTime in the editor in the inspector while the game is running to be empty not 0 just empty without any value the whole project freeze not responding and i need to shut it down.
the script that make the object moving :
using UnityEngine;
using UnityEngine.Events;
namespace BezierSolution
{
[AddComponentMenu( "Bezier Solution/Bezier Walker With Time" )]
[HelpURL( "https://github.com/yasirkula/UnityBezierSolution" )]
public class BezierWalkerWithTime : BezierWalker
{
public BezierSpline spline;
public TravelMode travelMode;
public float travelTime = 5f;
[SerializeField]
[Range( 0f, 1f )]
private float m_normalizedT = 0f;
public bool highQuality = false;
public override BezierSpline Spline { get { return spline; } }
public override float NormalizedT
{
get { return m_normalizedT; }
set { m_normalizedT = value; }
}
public float movementLerpModifier = 10f;
public float rotationLerpModifier = 10f;
public LookAtMode lookAt = LookAtMode.Forward;
private bool isGoingForward = true;
public override bool MovingForward { get { return isGoingForward; } }
public UnityEvent onPathCompleted = new UnityEvent();
private bool onPathCompletedCalledAt1 = false;
private bool onPathCompletedCalledAt0 = false;
private void Update()
{
Execute( Time.deltaTime );
}
public override void Execute( float deltaTime )
{
float _normalizedT = highQuality ? spline.evenlySpacedPoints.GetNormalizedTAtPercentage( m_normalizedT ) : m_normalizedT;
transform.position = Vector3.Lerp( transform.position, spline.GetPoint( _normalizedT ), movementLerpModifier * deltaTime );
if( lookAt == LookAtMode.Forward )
{
BezierSpline.Segment segment = spline.GetSegmentAt( _normalizedT );
Quaternion targetRotation;
if( isGoingForward )
targetRotation = Quaternion.LookRotation( segment.GetTangent(), segment.GetNormal() );
else
targetRotation = Quaternion.LookRotation( -segment.GetTangent(), segment.GetNormal() );
transform.rotation = Quaternion.Lerp( transform.rotation, targetRotation, rotationLerpModifier * deltaTime );
}
else if( lookAt == LookAtMode.SplineExtraData )
transform.rotation = Quaternion.Lerp( transform.rotation, spline.GetExtraData( _normalizedT, extraDataLerpAsQuaternionFunction ), rotationLerpModifier * deltaTime );
if( isGoingForward )
{
m_normalizedT += deltaTime / travelTime;
if( m_normalizedT > 1f )
{
if( travelMode == TravelMode.Once )
m_normalizedT = 1f;
else if( travelMode == TravelMode.Loop )
m_normalizedT -= 1f;
else
{
m_normalizedT = 2f - m_normalizedT;
isGoingForward = false;
}
if( !onPathCompletedCalledAt1 )
{
onPathCompletedCalledAt1 = true;
#if UNITY_EDITOR
if( UnityEditor.EditorApplication.isPlaying )
#endif
onPathCompleted.Invoke();
}
}
else
{
onPathCompletedCalledAt1 = false;
}
}
else
{
m_normalizedT -= deltaTime / travelTime;
if( m_normalizedT < 0f )
{
if( travelMode == TravelMode.Once )
m_normalizedT = 0f;
else if( travelMode == TravelMode.Loop )
m_normalizedT += 1f;
else
{
m_normalizedT = -m_normalizedT;
isGoingForward = true;
}
if( !onPathCompletedCalledAt0 )
{
onPathCompletedCalledAt0 = true;
#if UNITY_EDITOR
if( UnityEditor.EditorApplication.isPlaying )
#endif
onPathCompleted.Invoke();
}
}
else
{
onPathCompletedCalledAt0 = false;
}
}
}
}
}
the class BezierWalker
using UnityEngine;
namespace BezierSolution
{
public enum TravelMode { Once = 0, Loop = 1, PingPong = 2, Pause = 0 };
public enum LookAtMode { None = 0, Forward = 1, SplineExtraData = 2 }
public abstract class BezierWalker : MonoBehaviour
{
public abstract BezierSpline Spline { get; }
public abstract bool MovingForward { get; }
public abstract float NormalizedT { get; set; }
public abstract void Execute( float deltaTime );
public static readonly ExtraDataLerpFunction extraDataLerpAsQuaternionFunction = InterpolateExtraDataAsQuaternion;
private static BezierPoint.ExtraData InterpolateExtraDataAsQuaternion( BezierPoint.ExtraData data1, BezierPoint.ExtraData data2, float normalizedT )
{
return Quaternion.LerpUnclamped( data1, data2, normalizedT );
}
}
}
in the BezierWalker script in the TravelMode enum i added the variable Pause = 0
maybe i can use it in the BezierWalkerWithTime for pausing for example if the value in travelTime is empty then just pause the object from moving instead make the whole project not responding and freezing. and then if typing some value more then 0 make the object moving again.

transfer damage based on the selected object

There are three scripts
1)Checks the mouse click on the object (unit), if it is a unit, then the backlight is turned on, this object is recorded in the target mob s variable. (everything is cool here, I even passed the targetmobs variable to the 2 script)
if the space key is pressed, then we must damage the selected target (based on targetmobs)(not working)
here are the characteristics of the unit (in particular health)
The problem is in accessing the variable based on the selected object
I attach the code
1)
public class Select : MonoBehaviour
{
public bool IsActive ;
public Camera selectCamera;
public GameObject[] mobs;
public GameObject targetmobs;
private RaycastHit hit;
bool selecting = false;
private float selectTimer = 0f;
void Awake()
{
mobs = GameObject.FindGameObjectsWithTag("Skelet");
}
void Start()
{
}
void Update()
{
Debug.Log(IsActive);
if (Input.GetMouseButtonDown(0))
{
CheckIfUnderMouse();
}
}
public void CheckIfUnderMouse()
{
Ray ray = selectCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100f))
{
if (hit.collider.gameObject.tag == "Skelet")
{
targetmobs = hit.collider.gameObject;
targetmobs.GetComponentInChildren<SelectableCharacter>().TurnOnSelector();
testdamagetounits.target = targetmobs;
Debug.Log("нажал и выбрал");
IsActive = true;
}
else
{
IsActive = false;
if(targetmobs != null)
{
targetmobs.GetComponentInChildren<SelectableCharacter>().TurnOffSelector();
targetmobs = null;
testdamagetounits.target = null;
}
Debug.Log("нажал в пустоту");
}
}
}
}
public class testdamagetounits : MonoBehaviour
{
int randomNumber;
int lastNumber;
int meleeDamage = 5;
int takedamage;
public static GameObject target;
void Start()
{
target = null;
randomNumber = Random.Range(0, 5);
}
void Update()
{
Randomize();
if (Input.GetKeyDown(KeyCode.Space))
{
tuTarget();
}
}
void Randomize()
{
randomNumber = Random.Range(0, 5);
if (randomNumber == lastNumber)
{
randomNumber = Random.Range(0, 5);
}
lastNumber = randomNumber;
}
void tuTarget()
{
if(target != null)
{
}
}
}
public class Target : MonoBehaviour
{
int randomNumber;
int lastNumber;
int damage;
public TextMeshProUGUI TextHealth;
public TextMeshProUGUI TextDamage;
public TargetHealthBar healthBar;
[Header("Характеристики")]
public int maxHealth = 122;
public int currentHealth;
void Start()
{
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
SelectHealth.currentHealth = currentHealth;
SelectHealth.maxHealth = maxHealth;
TextHealth.text = currentHealth.ToString()+ "/"+maxHealth.ToString();
}
void Update()
{
TakeDamage();
}
void TakeDamage()
{
if(currentHealth <=0 )
{
}
else
{
currentHealth -= damage;
TextDamage.text = "-" + damage.ToString();
}
healthBar.SetHealth(currentHealth);
TextHealth.text = currentHealth.ToString()+ "/"+maxHealth.ToString();
}
}
пробовал разные обращения через GetComponentInChildren().
но увы я новичок в программировании

The type or namespace name 'Flock' could not be found (are you missing a using directive or an assembly reference?)

I get this error when trying this code on my 2D game:
Assets\Scripts\Enemy Spawn\FlockUnit.cs(28,26): error CS0246: The type
or namespace name 'Flock' could not be found (are you missing a using
directive or an assembly reference?)
Assets\Scripts\Enemy Spawn\FlockUnit.cs(16,10): error CS0246: The type
or namespace name 'Flock' could not be found (are you missing a using
directive or an assembly reference?)
This is the script:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlockUnit : MonoBehaviour
{
[SerializeField] private float FOVAngle;
[SerializeField] private float smoothDamp;
[SerializeField] private LayerMask obstacleMask;
[SerializeField] private Vector3[] directionsToCheckWhenAvoidingObstacles;
private List<FlockUnit> cohesionNeighbours = new List<FlockUnit>();
private List<FlockUnit> avoidanceNeighbours = new List<FlockUnit>();
private List<FlockUnit> aligementNeighbours = new List<FlockUnit>();
private Flock assignedFlock;
private Vector3 currentVelocity;
private Vector3 currentObstacleAvoidanceVector;
private float speed;
public Transform myTransform { get; set; }
private void Awake()
{
myTransform = transform;
}
public void AssignFlock(Flock flock)
{
assignedFlock = flock;
}
public void InitializeSpeed(float speed)
{
this.speed = speed;
}
public void MoveUnit()
{
FindNeighbours();
CalculateSpeed();
var cohesionVector = CalculateCohesionVector() * assignedFlock.cohesionWeight;
var avoidanceVector = CalculateAvoidanceVector() * assignedFlock.avoidanceWeight;
var aligementVector = CalculateAligementVector() * assignedFlock.aligementWeight;
var boundsVector = CalculateBoundsVector() * assignedFlock.boundsWeight;
var obstacleVector = CalculateObstacleVector() * assignedFlock.obstacleWeight;
var moveVector = cohesionVector + avoidanceVector + aligementVector + boundsVector + obstacleVector;
moveVector = Vector3.SmoothDamp(myTransform.forward, moveVector, ref currentVelocity, smoothDamp);
moveVector = moveVector.normalized * speed;
if (moveVector == Vector3.zero)
moveVector = transform.forward;
myTransform.forward = moveVector;
myTransform.position += moveVector * Time.deltaTime;
}
private void FindNeighbours()
{
cohesionNeighbours.Clear();
avoidanceNeighbours.Clear();
aligementNeighbours.Clear();
var allUnits = assignedFlock.allUnits;
for (int i = 0; i < allUnits.Length; i++)
{
var currentUnit = allUnits[i];
if (currentUnit != this)
{
float currentNeighbourDistanceSqr = Vector3.SqrMagnitude(currentUnit.myTransform.position - myTransform.position);
if (currentNeighbourDistanceSqr <= assignedFlock.cohesionDistance * assignedFlock.cohesionDistance)
{
cohesionNeighbours.Add(currentUnit);
}
if (currentNeighbourDistanceSqr <= assignedFlock.avoidanceDistance * assignedFlock.avoidanceDistance)
{
avoidanceNeighbours.Add(currentUnit);
}
if (currentNeighbourDistanceSqr <= assignedFlock.aligementDistance * assignedFlock.aligementDistance)
{
aligementNeighbours.Add(currentUnit);
}
}
}
}
private void CalculateSpeed()
{
if (cohesionNeighbours.Count == 0)
return;
speed = 0;
for (int i = 0; i < cohesionNeighbours.Count; i++)
{
speed += cohesionNeighbours[i].speed;
}
speed /= cohesionNeighbours.Count;
speed = Mathf.Clamp(speed, assignedFlock.minSpeed, assignedFlock.maxSpeed);
}
private Vector3 CalculateCohesionVector()
{
var cohesionVector = Vector3.zero;
if (cohesionNeighbours.Count == 0)
return Vector3.zero;
int neighboursInFOV = 0;
for (int i = 0; i < cohesionNeighbours.Count; i++)
{
if (IsInFOV(cohesionNeighbours[i].myTransform.position))
{
neighboursInFOV++;
cohesionVector += cohesionNeighbours[i].myTransform.position;
}
}
cohesionVector /= neighboursInFOV;
cohesionVector -= myTransform.position;
cohesionVector = cohesionVector.normalized;
return cohesionVector;
}
private Vector3 CalculateAligementVector()
{
var aligementVector = myTransform.forward;
if (aligementNeighbours.Count == 0)
return myTransform.forward;
int neighboursInFOV = 0;
for (int i = 0; i < aligementNeighbours.Count; i++)
{
if (IsInFOV(aligementNeighbours[i].myTransform.position))
{
neighboursInFOV++;
aligementVector += aligementNeighbours[i].myTransform.forward;
}
}
aligementVector /= neighboursInFOV;
aligementVector = aligementVector.normalized;
return aligementVector;
}
private Vector3 CalculateAvoidanceVector()
{
var avoidanceVector = Vector3.zero;
if (aligementNeighbours.Count == 0)
return Vector3.zero;
int neighboursInFOV = 0;
for (int i = 0; i < avoidanceNeighbours.Count; i++)
{
if (IsInFOV(avoidanceNeighbours[i].myTransform.position))
{
neighboursInFOV++;
avoidanceVector += (myTransform.position - avoidanceNeighbours[i].myTransform.position);
}
}
avoidanceVector /= neighboursInFOV;
avoidanceVector = avoidanceVector.normalized;
return avoidanceVector;
}
private Vector3 CalculateBoundsVector()
{
var offsetToCenter = assignedFlock.transform.position - myTransform.position;
bool isNearCenter = (offsetToCenter.magnitude >= assignedFlock.boundsDistance * 0.9f);
return isNearCenter ? offsetToCenter.normalized : Vector3.zero;
}
private Vector3 CalculateObstacleVector()
{
var obstacleVector = Vector3.zero;
RaycastHit hit;
if (Physics.Raycast(myTransform.position, myTransform.forward, out hit, assignedFlock.obstacleDistance, obstacleMask))
{
obstacleVector = FindBestDirectionToAvoidObstacle();
}
else
{
currentObstacleAvoidanceVector = Vector3.zero;
}
return obstacleVector;
}
private Vector3 FindBestDirectionToAvoidObstacle()
{
if (currentObstacleAvoidanceVector != Vector3.zero)
{
RaycastHit hit;
if (!Physics.Raycast(myTransform.position, myTransform.forward, out hit, assignedFlock.obstacleDistance, obstacleMask))
{
return currentObstacleAvoidanceVector;
}
}
float maxDistance = int.MinValue;
var selectedDirection = Vector3.zero;
for (int i = 0; i < directionsToCheckWhenAvoidingObstacles.Length; i++)
{
RaycastHit hit;
var currentDirection = myTransform.TransformDirection(directionsToCheckWhenAvoidingObstacles[i].normalized);
if (Physics.Raycast(myTransform.position, currentDirection, out hit, assignedFlock.obstacleDistance, obstacleMask))
{
float currentDistance = (hit.point - myTransform.position).sqrMagnitude;
if (currentDistance > maxDistance)
{
maxDistance = currentDistance;
selectedDirection = currentDirection;
}
}
else
{
selectedDirection = currentDirection;
currentObstacleAvoidanceVector = currentDirection.normalized;
return selectedDirection.normalized;
}
}
return selectedDirection.normalized;
}
private bool IsInFOV(Vector3 position)
{
return Vector3.Angle(myTransform.forward, position - myTransform.position) <= FOVAngle;
}
}
The error was just the name of the script it was FlockScript Instead of Flock by itself. and this is the script that was causing the problem
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Flock : MonoBehaviour
{
[Header("Spawn Setup")]
[SerializeField] private FlockUnit flockUnitPrefab;
[SerializeField] private int flockSize;
[SerializeField] private Vector3 spawnBounds;
[Header("Speed Setup")]
[Range(0, 10)]
[SerializeField] private float _minSpeed;
public float minSpeed { get { return _minSpeed; } }
[Range(0, 10)]
[SerializeField] private float _maxSpeed;
public float maxSpeed { get { return _maxSpeed; } }
[Header("Detection Distances")]
[Range(0, 10)]
[SerializeField] private float _cohesionDistance;
public float cohesionDistance { get { return _cohesionDistance; } }
[Range(0, 10)]
[SerializeField] private float _avoidanceDistance;
public float avoidanceDistance { get { return _avoidanceDistance; } }
[Range(0, 10)]
[SerializeField] private float _aligementDistance;
public float aligementDistance { get { return _aligementDistance; } }
[Range(0, 10)]
[SerializeField] private float _obstacleDistance;
public float obstacleDistance { get { return _obstacleDistance; } }
[Range(0, 100)]
[SerializeField] private float _boundsDistance;
public float boundsDistance { get { return _boundsDistance; } }
[Header("Behaviour Weights")]
[Range(0, 10)]
[SerializeField] private float _cohesionWeight;
public float cohesionWeight { get { return _cohesionWeight; } }
[Range(0, 10)]
[SerializeField] private float _avoidanceWeight;
public float avoidanceWeight { get { return _avoidanceWeight; } }
[Range(0, 10)]
[SerializeField] private float _aligementWeight;
public float aligementWeight { get { return _aligementWeight; } }
[Range(0, 10)]
[SerializeField] private float _boundsWeight;
public float boundsWeight { get { return _boundsWeight; } }
[Range(0, 100)]
[SerializeField] private float _obstacleWeight;
public float obstacleWeight { get { return _obstacleWeight; } }
public FlockUnit[] allUnits { get; set; }
private void Start()
{
GenerateUnits();
}
private void Update()
{
for (int i = 0; i < allUnits.Length; i++)
{
allUnits[i].MoveUnit();
}
}
private void GenerateUnits()
{
allUnits = new FlockUnit[flockSize];
for (int i = 0; i < flockSize; i++)
{
var randomVector = UnityEngine.Random.insideUnitSphere;
randomVector = new Vector3(randomVector.x * spawnBounds.x, randomVector.y * spawnBounds.y, randomVector.z * spawnBounds.z);
var spawnPosition = transform.position + randomVector;
var rotation = Quaternion.Euler(0, UnityEngine.Random.Range(0, 360), 0);
allUnits[i] = Instantiate(flockUnitPrefab, spawnPosition, rotation);
allUnits[i].AssignFlock(this);
allUnits[i].InitializeSpeed(UnityEngine.Random.Range(minSpeed, maxSpeed));
}
}
}

sending an RPC with class instance give an error - unity Netcode

I'm using NetCode for GameObject 1.0.0 pre.5 in unity
and I keep getting the following error when I'm trying to send a ServerRPC
Assets\scrips\Weapons\Grenades.cs(72,13): error - Don't know how to serialize PlayerMessenger - implement INetworkSerializable or add an extension method for FastBufferWriter.WriteValueSafe to define serialization.
the method that give the error is Grenades.SetHealthDownServerRpc()
how take's an PlayerMassenger class instace
here's the my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
namespace BeanBoxers.Weapons
{
[System.Serializable]
[implement : INetworkSerializable]
public class Grenades : NetworkBehaviour
{
public string PlayerTag;
public GameObject Particals;
public double Timer = 10;
public bool IsThouned = false;
public bool? Team {get; private set;} = null;
public float HitRadius = 5;
public float Demage = 120;
public float effectTime = .15f;
void Start()
{
Particals.SetActive(false);
if(!IsServer) {return;}
GetComponent<NetworkObject>().Spawn();
}
// Update is called once per frame
void Update()
{
if (!IsThouned) {return; }
else
{
Timer -= Time.deltaTime;
}
if (Timer <= 0)
{
explod();
}
}
public void explod()
{
Particals.SetActive(true);
IsThouned = false;
Collider[] hitColliders = Physics.OverlapSphere(transform.position, HitRadius);
foreach (var hitCollider in hitColliders)
{
if (!IsOwner) {break;}
if (hitCollider.tag == PlayerTag)
{
BeanBoxers.Player.PlayerMessenger Player = hitCollider.gameObject.GetComponent<BeanBoxers.Player.PlayerMessenger>();
if (Player.Team != Team || Team == null)
{
Vector3 HitDistanceVec3 = hitCollider.gameObject.transform.position - transform.position;
float Distance = Mathf.Abs(Mathf.Sqrt(HitDistanceVec3.x * HitDistanceVec3.x + HitDistanceVec3.y * HitDistanceVec3.y + HitDistanceVec3.z * HitDistanceVec3.z));
SetHealthDownServerRpc(Player ,Mathf.Abs(Mathf.Sin(90 / Distance)) * Demage);
}
}
}
GetComponent<MeshRenderer>().enabled = false;
Destroy(transform.gameObject, effectTime);
}
public void setTeam(bool? team)
{
Team = team;
}
[ServerRpc]
private void SetHealthDownServerRpc(BeanBoxers.Player.PlayerMessenger player, float Demage)
{
player.SetHealth(player.GetHealth() - Demage);
}
}
}
PlayerMassenger:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
using TMPro;
namespace BeanBoxers.Player
{
[System.Serializable]
public class PlayerMessenger : NetworkBehaviour
{
protected static BeanBoxers.Guns.GunsTM GunsTaskManager = new BeanBoxers.Guns.GunsTM();//Managed the guns
//you can get from him a gun like so: GunsTaskManager.GetGun(<Gun name>);
public LayerMask groundMask;//a ground mask
public dynamic Gun{get; private set;}// store the gun from the GunsTM to a variable
public GameObject groundCheck{get; private set;}// store the GameObject that checks if the player touching
public CharacterController controller{get; private set;}// control the player
public GameObject GrenadePath{get; private set;}//store the force for the grande to fly to
private int MaxHealth = 100;//max health
public NetworkVariable<float> Health{get; private set;} = new NetworkVariable<float>(100);//my health
public float HealthRegnertion{get; private set;} = 3;// how fast the player does regnertion
public float gravity = -10.0f;//gravity
public float speed{get; private set;} = 100;//current speed
public float Ospeed{get; private set;}// oriaginal speed
private float groundDistnce = 0.4f;//the radus of the spire that chack if the payer touching th ground
private Vector3 velocity = new Vector3(0, 0, 0);//the player velocity
public float JumpVelocity{get; private set;} = 10f;// jump velocity
private bool isGrounded;// store if the player is grouded or not
public bool isSlideing{get; private set;} = false;//store if the player is slideing or not
private Vector3 slideScale = new Vector3(1.3f, 0.5f, 1.3f);//player scale
public float MaxSlideTime{get; private set;} = 10;// max slideing time
public float SlideingTime{get; private set;} = 0;//current slideing time
public bool isDead{get; private set;} = false;//is the player dead
private float RespawnTime = 5f;//how mach time is take the player to do a respawn
public bool? Team{get; private set;} = null;//true; red team, false; blue team, null; free for all
private string GunName = "PickerKicker";// my current gun name
public bool ShootTriger{get; private set;} = false;// am I polling the triger
public int GrandesLeft{get; private set;} = 3;
public int MaxNumberOfHoldedGrenades{get; private set;} = 3;
public bool IsHoldingGrenade{get; private set;} = false;
public float GrandeHoldTimer{get; private set;} = 0;
public float MaxHoldGrandeTime{get; private set;} = 5;
public int SmookeGrandesLeft{get; private set;} = 3;
public int MaxNumberOfHoldSmookeGrenades{get; private set;} = 3;
public bool IsHoldingSmookeGrenade{get; private set;} = false;
public float SmookeGrandeHoldTimer{get; private set;} = 0;
public float MaxHoldSmookeGrandeTime{get; private set;} = 5;
public int MortarLeft{get; private set;} = 3;
public int MaxNumberOfHoldedMortor{get; private set;} = 6;
public RayCheck Ray{get; private set;}// a RayCheck object
private GameObject UI;
private BeanBoxers.UI.Player.FaceTheCamera UIclass;
public double timer{get; private set;} = 0;// a timer
public NetworkVariable<bool> TryVariable = new NetworkVariable<bool>(false);
void Start()
{
groundCheck = transform.GetChild(0).gameObject;
Ospeed = speed;
controller = GetComponent<CharacterController>();
groundCheck.transform.parent = this.transform;
groundCheck.transform.localPosition = new Vector3(0, -1f, 0);
Ray = this.GetComponent<RayCheck>();
this.SetGunName(GunName);
EasterEggs();
groundMask = LayerMask.GetMask("Ground");
this.transform.position = new Vector3(0f, 10f, 0f);
if (IsOwner)
{
SetName(GameObject.Find("Menu").GetComponent<BeanBoxers.Multiplayer.MainMenu.MainMenu>().Name);
}
}
void Update()
{
//update UI
UIclass.update(this.transform.position, Health.Value, MaxHealth, name);
if (!isDead)
{
print(TryVariable);
//update
slideUpdate();
velocity.y += gravity * Time.deltaTime;
Vector3 move = new Vector3(velocity.x * speed, velocity.y, velocity.x * speed);
controller.Move(move * Time.deltaTime);
isGrounded = Physics.CheckSphere(groundCheck.transform.position, groundDistnce, groundMask);
if (isGrounded && velocity.y <= 0)
{
velocity.y = -2f;
}
//update the gun
Gun.Update();
//update the grenade
if (IsHoldingGrenade)
{
if (GrandeHoldTimer > MaxHoldGrandeTime)
{
GrandeHoldTimer = MaxHoldGrandeTime;
}
else
{
GrandeHoldTimer += Time.deltaTime;
}
}
//update the smooke grenade
if (IsHoldingSmookeGrenade)
{
if (SmookeGrandeHoldTimer > MaxHoldSmookeGrandeTime)
{
SmookeGrandeHoldTimer = MaxHoldSmookeGrandeTime;
}
else
{
SmookeGrandeHoldTimer += Time.deltaTime;
}
}
//check the ray cast
if (ShootTriger)
{
if (Gun.Shoot())
{
PlayerMessenger output = Ray.CheckWhatRayHit();
if (output != null)
{
output.SetHealth(output.GetHealth() - Gun.TakeDemage(this.transform.position, output.transform.position));
}
}
}
if (Health.Value <= 0)
{
isDead = true;
// ServerRpc();
if (!IsOwner) {return;}
DiedServerRpc();
//make Sure the player position update when he die
Disable();
Invoke("Spawn", 5);
}
else if (Health.Value < MaxHealth)
{
Health.Value += HealthRegnertion * Time.deltaTime;
}
}
}
public void Spawn()
{
Enable();
isDead = false;
timer = 0;
Health.Value = MaxHealth;
GrandesLeft = MaxNumberOfHoldedGrenades;
SmookeGrandesLeft = MaxNumberOfHoldSmookeGrenades;
MortarLeft = MaxNumberOfHoldedMortor;
}
public void SetGunName(string gunName)
{
if (!IsServer) {return;}
this.GunName = gunName;
Gun = GunsTaskManager.GetGun(GunName);
Gun.setParent(Ray.RayStarter);
}
public string GetGunName()
{
return GunName;
}
public void SetName(string name)
{
if (!IsServer) {return;}
this.name = name;
EasterEggs();
}
public string GetName(string name)
{
return name;
}
public void SetHealth(float Health)
{
if (!IsServer) {return;}
this.Health.Value = Health;
if (Health > 0) {return;}
DiedServerRpc();
}
public float GetHealth()
{
return Health.Value;
}
[ServerRpc]
private void DiedServerRpc()
{
DiedClientRpc();
}
[ClientRpc]
private void DiedClientRpc()
{
if (IsOwner) {return;}
//make Sure the player position update when he die
isDead = true;
Disable();
Invoke("Spawn", 5);
}
public void SetSpeed(float NewSpeed)
{
if (!IsServer) {return;}
speed = NewSpeed;
}
public void SetMaxHealth(int Max_Health)
{
if (!IsServer) {return;}
MaxHealth = Max_Health;
}
public void changeTeam(bool? team)
{
if (!IsServer) {return;}
Team = team;
}
private void Disable()
{
transform.gameObject.SetActive(false);
}
private void Enable()
{
transform.gameObject.SetActive(true);
}
private void EasterEggs()
{
if (name == "Eti Ben Simon") {MaxHealth *= 2; Health.Value = MaxHealth;}
}
public void shootTriger(bool val)
{
ShootTriger = val;
shootTrigerServerRpc(val);
}
[ServerRpc]
private void shootTrigerServerRpc(bool val)
{
ShootTriger = val;
shootTrigerClientRpc(val);
}
[ClientRpc]
private void shootTrigerClientRpc(bool val)
{
if(IsOwner) {return;}
ShootTriger = val;
}
public void Jump()
{
if(!IsOwner) {return;}
JumpServerRpc();
if (isGrounded)
{
velocity.y = JumpVelocity;
unslide();
}
}
[ServerRpc]
private void JumpServerRpc()
{
JumpClientRpc();
}
[ClientRpc]
private void JumpClientRpc()
{
if (isGrounded)
{
velocity.y = JumpVelocity;
unslide();
}
}
public void slide()
{
if(!IsOwner) {return;}
slideServerRpc();
if (isGrounded)
{
speed = Ospeed * 2;
isSlideing = true;
transform.localScale = slideScale;
}
}
[ServerRpc]
private void slideServerRpc()
{
slideClientRpc();
speed = Ospeed;
isSlideing = false;
Vector3 newScale = new Vector3(1f, 1f, 1f);
transform.localScale = newScale;
}
[ClientRpc]
private void slideClientRpc()
{
if(IsOwner) {return;}
if (isGrounded)
{
speed = Ospeed * 2;
isSlideing = true;
transform.localScale = slideScale;
}
}
public void unslide()
{
if(!IsOwner) {return;}
unslideServerRpc();
speed = Ospeed;
isSlideing = false;
Vector3 newScale = new Vector3(1f, 1f, 1f);
transform.localScale = newScale;
}
[ServerRpc]
private void unslideServerRpc()
{
unslideClientRpc();
speed = Ospeed;
isSlideing = false;
Vector3 newScale = new Vector3(1f, 1f, 1f);
transform.localScale = newScale;
}
[ClientRpc]
private void unslideClientRpc()
{
if(IsOwner) {return;}
speed = Ospeed;
isSlideing = false;
Vector3 newScale = new Vector3(1f, 1f, 1f);
transform.localScale = newScale;
}
public void slideUpdate()
{
if (isSlideing)
{
SlideingTime += Time.deltaTime;
}
else
{
SlideingTime -= Time.deltaTime / 2;
if (SlideingTime < 0)
{
SlideingTime = 0;
}
}
if (SlideingTime >= MaxSlideTime)
{
unslide();
}
}
public void ThrowGrenade()
{
if (!IsOwner) {return;}
if (GrandesLeft > 0)
{
Debug.Log("Grenade.Throw");
GameObject Grande = Instantiate(Resources.Load("3Dmodels/Weapons/Grenade")) as GameObject;
Grande.transform.position = GrenadePath.transform.position;
BeanBoxers.Weapons.Grenades G = Grande.GetComponent<BeanBoxers.Weapons.Grenades>();
Rigidbody GrenadeRigidbody = Grande.GetComponent<Rigidbody>();
G.setTeam(Team);
G.IsThouned = true;
GrenadeRigidbody.AddForce((GrenadePath.transform.position - transform.position) * GrandeHoldTimer * 170);
GrenadeRigidbody.AddTorque(new Vector3(UnityEngine.Random.Range(-180, 180), UnityEngine.Random.Range(-180, 180), UnityEngine.Random.Range(-180, 180)));
GrandeHoldTimer = 0;
IsHoldingGrenade = false;
GrandesLeft -= 1;
}
}
public void isHoldingGrenade(bool val)
{
if (!IsOwner) {return;}
IsHoldingGrenade = val;
}
[ServerRpc]
private void IsHoldingGrenadeServerRpc(bool val)
{
IsHoldingGrenade = val;
IsHoldingGrenadeClientRpc(val);
}
[ClientRpc]
private void IsHoldingGrenadeClientRpc(bool val)
{
if (IsOwner) {return;}
IsHoldingGrenade = val;
}
public void ThrowSmookeGrenade()
{
if (!IsOwner) {return;}
if (SmookeGrandesLeft < 0) {return;}
Debug.Log("SmookeGrenade.Throw");
GameObject Grande = Instantiate(Resources.Load("3Dmodels/Weapons/SmookeGrenade")) as GameObject;
Grande.transform.position = GrenadePath.transform.position;
BeanBoxers.Weapons.Grenades G = Grande.GetComponent<BeanBoxers.Weapons.Grenades>();
Rigidbody GrenadeRigidbody = Grande.GetComponent<Rigidbody>();
G.setTeam(Team);
G.IsThouned = true;
GrenadeRigidbody.AddForce((GrenadePath.transform.position - transform.position) * SmookeGrandeHoldTimer * 170);
GrenadeRigidbody.AddTorque(new Vector3(UnityEngine.Random.Range(-180, 180), UnityEngine.Random.Range(-180, 180), UnityEngine.Random.Range(-180, 180)));
SmookeGrandeHoldTimer = 0;
IsHoldingSmookeGrenade = false;
SmookeGrandesLeft -= 1;
}
public void isHoldingSmookeGrenade(bool val)
{
if (!IsOwner) {return;}
IsHoldingSmookeGrenade = val;
}
[ServerRpc]
private void IsHoldingSmookeGrenadeServerRpc(bool val)
{
IsHoldingSmookeGrenade = val;
IsHoldingSmookeGrenadeClientRpc(val);
}
[ClientRpc]
private void IsHoldingSmookeGrenadeClientRpc(bool val)
{
if (IsOwner) {return;}
IsHoldingSmookeGrenade = val;
}
public void PutMortar()
{
if (!IsOwner) {return;}
if (MortarLeft < 0) {return;}
GameObject mortor = Instantiate(Resources.Load("3Dmodels/Weapons/Mortor")) as
GameObject;
mortor.transform.position = GrenadePath.transform.position;
mortor.transform.Rotate(46f, GrenadePath.transform.eulerAngles.y + 180, -90f);
MortarLeft -= 1;
}
}
}
my scripts aren't the best, I know but anybody have any idea why I get the error? it will very help me
I guess you could first off try to do what the error says: "Implement INetworkSerializable". To Implement that Interface you would write: ...Grenades : Networkbehavior, INetworkSerializable. I don't know if [implement: ...] works so that is just a guess based off of your error.

I get an error in the Unity console. I like to know what is means and how to solve it?

I tried to get the player ship game object to move to the next scene if all enemies are killed and won the game. I get an error in the Unity console says:
Assets\Scripts\GameController.cs(57,25): error CS0122: 'SceneLoader.LoadNextScene()' is inaccessible due to its protection level.
Currently, I can only go to the next scene when I change the value in the of this line:
SceneManager.LoadScene(1);
to (2) in the scene Loader.cs I added code to the game controller this here: the public void WinGame() method any feedback to what this error s means and how I can fix it is appreciated. :)
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneLoader : MonoBehaviour
{
[SerializeField] float levelLoadDelay = 2f;
private int currentSceneIndex = -1;
private void Awake()
{
currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
}
private void Start()
{
if (currentSceneIndex == 0)
{
Invoke("LoadFirstScene", 2f);
}
private void LoadNextScene()
{
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
int nextSceneIndex = currentSceneIndex + 1;
SceneManager.LoadScene(nextSceneIndex);
}
public void LoadFirstScene()
{
SceneManager.LoadScene(1);
}
}
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.UI;
public class GameController : MonoBehaviour
{
public Text scoreText;
public Text restartText;
public Text gameOverText;
[SerializeField] private Text outcome;
[SerializeField] private PlayableDirector masterTimelinePlayableDirector;
[SerializeField] private GameObject playerShip;
private bool winGame = false;
private bool gameOver = false;
private int score;
private int enemiesLeft = 0;
private SceneLoader sceneLoader;
public bool allEnemiesKilled;
public float enemiesInScene = 10.0f;
public float enemiesKilled;
void Start()
{
sceneLoader = FindObjectOfType<SceneLoader>();
enemiesLeft = GameObject.FindObjectsOfType<Enemy>().Length;
restartText.text = "";
gameOverText.text = "";
outcome.text = "";
score = 0;
UpdateScore();
}
void Update()
{
if (gameOver)
{
if (Input.GetKeyDown(KeyCode.R))
{
sceneLoader.LoadFirstScene();
}
}
if (PlayerHealth.cur_health <= 0)
{
GameOver();
}
}
public void WinGame()
{
if (enemiesKilled < enemiesInScene)
{
allEnemiesKilled = true;
}
sceneLoader.LoadNextScene();
}
public void DecreaseEnemyCount()
{
enemiesLeft--;
}
public void AddScore(int newScoreValue)
{
score += newScoreValue;
UpdateScore();
}
void UpdateScore()
{
scoreText.text = "Score: " + score;
}
public void GameOver()
{
gameOver = true;
gameOverText.text = "Game Over!";
if (enemiesLeft > 0)
{
outcome.text = "You Lose";
}
else
{
outcome.text = "You Win";
}
restartText.text = "Press 'R' for Restart";
masterTimelinePlayableDirector.Stop();
playerShip.SetActive(false);
}
}
With your current code structure, the problem is that you have method defined inside the start function.
Modified script:
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneLoader : MonoBehaviour
{
[SerializeField] float levelLoadDelay = 2f;
private int currentSceneIndex = -1;
public static SceneLoader instance;
private void Awake()
{
currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
instance = this;
}
private void Start()
{
if (currentSceneIndex == 0)
{
Invoke("LoadFirstScene", 2f);
}
}
public void LoadNextScene()
{
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
int nextSceneIndex = currentSceneIndex + 1;
SceneManager.LoadScene(nextSceneIndex);
}
public void LoadFirstScene()
{
SceneManager.LoadScene(1);
}
You can now call the LoadNextScene by using the code:
SceneLoader.instance.LoadNextScene();

Categories

Resources