Object don't exclude from list - c#

Me need exclude object from the list, i make it as other variants, but it don't work? Why?
I make destroy block as minecraft, but i can see just no thing =/ and i make as can doing.
Code:
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
public class GetTarget : MonoBehaviour
{
[Header("Координаты блока")] // positions blocks
public int positionX;
public int positionY;
public int positionZ;
[Header("Получение цели")] // get target
public static List<GameObject> target = new List<GameObject>();
private void OnTriggerStay(Collider collider) // check on touch to trigger
{
if(collider.gameObject.name == "WorldMap") { return; }
else if(collider.gameObject.name == "Water") { return; }
else if(collider.gameObject.name == "Berries") { return; } // this details in the code don't work now.
else
{
target.Insert(0, collider.gameObject);
Debug.Log("Вы получили " + target[0]); // Вы получите = You can have target[0] now
}
}
private void Update() // set round position
{
Vector3 positions = transform.position;
positionX = (int)Mathf.Round(gameObject.transform.position.x);
positionY = (int)Mathf.Round(gameObject.transform.position.y);
positionZ = (int)Mathf.Round(gameObject.transform.position.z);
positions.x = positionX;
positions.y = positionY;
positions.z = positionZ;
}
}
Thank you to everyone!

Related

How do i add multiple enemies to my unity wave system?

I have a wave script for my game and it works fine, however after a while I have realised it gets quite dull fighting against the same enemies over and over again, so I was wondering if I could make a list of some sort to store all enemies that will be in each wave.
Here is my script;
SpawnManager.cs
using System.Collections;
using UnityEngine;
[System.Serializable]
public class Wave
{
public int EnemiesPerWave;
public GameObject Enemy;
}
public class SpawnManager : MonoBehaviour
{
public Wave[] Waves; // class to hold information per wave
public Transform[] SpawnPoints;
public float TimeBetweenEnemies = 2f;
public GameObject HelpText;
public GameObject Shop;
public GameObject shopfx;
public Transform ShopL;
bool shopactive = false;
private int _totalEnemiesInCurrentWave;
private int _enemiesInWaveLeft;
private int _spawnedEnemies;
private int _currentWave;
private int _totalWaves;
void Start ()
{
_currentWave = -1; // avoid off by 1
_totalWaves = Waves.Length - 1; // adjust, because we're using 0 index
StartNextWave();
}
void Update()
{
if (_enemiesInWaveLeft <= 0 && Input.GetKeyDown(KeyCode.R))
{
StartNextWave();
}
}
void StartNextWave()
{
_currentWave++;
// win
if (_currentWave > _totalWaves)
{
return;
}
_totalEnemiesInCurrentWave = Waves[_currentWave].EnemiesPerWave;
_enemiesInWaveLeft = 0;
_spawnedEnemies = 0;
StartCoroutine(SpawnEnemies());
}
// Coroutine to spawn all of our enemies
IEnumerator SpawnEnemies()
{
GameObject enemy = Waves[_currentWave].Enemy;
while (_spawnedEnemies < _totalEnemiesInCurrentWave)
{
_spawnedEnemies++;
_enemiesInWaveLeft++;
int spawnPointIndex = Random.Range(0, SpawnPoints.Length);
// Create an instance of the enemy prefab at the randomly selected spawn point's
// position and rotation.
Instantiate(enemy, SpawnPoints[spawnPointIndex].position,
SpawnPoints[spawnPointIndex].rotation);
yield return new WaitForSeconds(TimeBetweenEnemies);
}
yield return null;
}
// called by an enemy when they're defeated
public void EnemyDefeated()
{
_enemiesInWaveLeft--;
// We start the next wave once we have spawned and defeated them all
if (_enemiesInWaveLeft == 0 && _spawnedEnemies == _totalEnemiesInCurrentWave)
{
HelpText.SetActive(true);
Invoke("SetFalse",5.0f);
Shop.SetActive(true);
Invoke("LateUpdate",1f);
Instantiate(shopfx, new Vector3(ShopL.transform.position.x, ShopL.transform.position.y, ShopL.transform.position.z), Quaternion.identity);
shopactive = true;
}
}
void SetFalse()
{
HelpText.SetActive(false);
}
void LateUpdate()
{
if(Input.GetKeyDown(KeyCode.R) && shopactive == true)
{
Shop.SetActive(false);
Instantiate(shopfx, new Vector3(Shop.transform.position.x, Shop.transform.position.y, Shop.transform.position.z), Quaternion.identity);
shopactive = false;
}
}
}

How to Instantiate circles all over the canvas unity(Mandelbrot set)

i am trying to Make The Mandelbrot set, i have the function thing working, zn = zn^
and i want to Visualizing the Mandelbrot set using circles, i tried this code but it cruses every time i compile, here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PaintMand : MonoBehaviour
{
[SerializeField] private GameObject CirclePaint;
[SerializeField] private RectTransform RedCircle;
[SerializeField] private Canvas canvas;
private float sumDistance = 0;
private bool HasFinshed = false;
private Vector2 start = new Vector2(2.133f,0.976f);
private void Update()
{
if (!HasFinshed)
{
sumDistance = AutoAxis.GetSumDistance();
MoveRed();
LoadRed();
}
}
public void MoveRed()
{
if(start.y < -0.988f)
{
HasFinshed = true;
}
else if(start.x <= -2.107f)
{
start.x = 2.133f;
start.y -= 0.20f;
}
else
{
start.x -= 0.20f;
}
RedCircle.anchoredPosition = start;
}
public void LoadRed()
{
if (IsUnstable())
{
GameObject NewCircle = Instantiate(CirclePaint, Vector3.zero,Quaternion.identity);
NewCircle.GetComponent<Image>().color = new Color(sumDistance,sumDistance,sumDistance);
NewCircle.transform.SetParent(canvas.transform);
NewCircle.GetComponent<RectTransform>().anchoredPosition = RedCircle.anchoredPosition;
}
}
private bool IsUnstable()
{
if(sumDistance > 1000)
{
return true;
}
return false;
}
}
the red circle is the c in the equation, zn = zn^ + c
and it moves every frame and checks if its unstable(the autoaxis is the class that makes the Visualizing the function) it gets the sum of the distance between all the circles and sends the float to the paintmad class, this cruses every time, pls help :(

How can I change the moving objects speed at runtime?

The manager script
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class DronesManager : MonoBehaviour
{
public GameObject target;
public float movementSpeed;
public float launchTime;
public Transform dronesUnchild;
private List<GameObject> drones = new List<GameObject>();
private float currentDroneSpeed;
private void Awake()
{
currentDroneSpeed = movementSpeed;
}
// Start is called before the first frame update
void Start()
{
target = GameObject.Find("Base");
drones = GameObject.FindGameObjectsWithTag("Drone").ToList();
StartCoroutine(MoveDrone());
}
// Update is called once per frame
void Update()
{
if(currentDroneSpeed != movementSpeed)
{
for(int i = 0; i < drones.Count; i++)
{
var droneControl = drones[i].GetComponent<DroneControl>();
droneControl.movingSpeed = movementSpeed;
}
currentDroneSpeed = movementSpeed;
}
}
private IEnumerator MoveDrone()
{
// same as you did:
drones = GameObject.FindGameObjectsWithTag("Drone").ToList();
foreach(var drone in drones)
{
drone.GetComponent<DroneControl>().target = target.transform;
}
while (drones.Count > 0)
{
// pick one at random, get it
int index = Random.Range(0, drones.Count);
var drone = drones[index];
// remove it from list
drones.RemoveAt(index);
// TODO: might want to check/guard if drone == null ... this guards against it
// being Destroy()ed and yet still lying around in our list marked as "dead"
// simplified your get-component-and-go-if-not-already-going code here
var droneControl = drone.GetComponent<DroneControl>();
if (droneControl.go == false)
{
droneControl.movingSpeed = movementSpeed;
droneControl.go = true;
drone.transform.parent = dronesUnchild;
}
// wait
yield return new WaitForSeconds(launchTime);
}
}
}
I tried to add this part in the Update
void Update()
{
if(currentDroneSpeed != movementSpeed)
{
for(int i = 0; i < drones.Count; i++)
{
var droneControl = drones[i].GetComponent<DroneControl>();
droneControl.movingSpeed = movementSpeed;
}
currentDroneSpeed = movementSpeed;
}
}
and this script is attached to each moving object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DroneControl : MonoBehaviour
{
public Transform target;
public float turnSpeed = .01f;
Quaternion rotGoal;
Vector3 direction;
public float movingSpeed;
public bool go = false;
private bool waitBeforeRotate = false;
private bool startRotating = false;
#region AddedCode
public float targetRange = 1.0f;
private bool IsTargetReached(Vector3 dronePos, Vector3 targetPos)
{
var distance = Vector3.Distance(dronePos, targetPos);
return distance < targetRange;
}
#endregion AddedCode
// Update is called once per frame
void Update()
{
// next line is modified to incorporate the range check
if (go && !IsTargetReached(transform.position, target.position))
{
transform.position += transform.forward * movingSpeed * Time.deltaTime;
if (waitBeforeRotate == false)
{
StartCoroutine(StartRotating());
waitBeforeRotate = true;
}
if (startRotating)
{
direction = (target.position - transform.position).normalized;
rotGoal = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, rotGoal, turnSpeed);
}
}
}
IEnumerator StartRotating()
{
yield return new WaitForSeconds(3f);
startRotating = true;
}
}
but it's never change the speed of moving objects.
if the speed of each moving object in the editor start is 5 for example and in the manager script I change the speed to 100 the speed of each object is still 5.
Maybe this is happening because after picking a random drone in IEnumerator you instantly remove it from the list?
So in Update() you set a speed for all drones, except the ones that are already moving.

Player not moving to all waypoints.

Enemy character not moving to the 3rd waypoint. After moving to waypoint 2 it just stops and the idle animation plays. The character has a NavMeshAgent on it and it looks like the destination reached event is not being triggered when he gets to the waypoint. If anyone has had a situation like this before I would appreciate any information possible. I have been trying to figure out whats wrong for a few hours now and am starting to think it might not be any of the scripts.
here is the waypoint controller
using UnityEngine;
using UnityEngine.AI;
public class WaypointController : MonoBehaviour {
Waypoints[] waypoints;
public Transform target;
//NavMeshPath path;
int currentWaypointIndex = -1;
//private NavMeshAgent agent;
//EnemyCharacter enemy;
public event System.Action<Waypoints> OnWaypointChanged;
// Use this for initialization
void Awake () {
waypoints = GetWaypoints();
}
public void SetNextWaypoint() {
if (currentWaypointIndex != waypoints.Length)
currentWaypointIndex++;
if (currentWaypointIndex == waypoints.Length)
currentWaypointIndex = 0;
if (OnWaypointChanged != null)
OnWaypointChanged(waypoints[currentWaypointIndex]);
//Debug.Log("OnWaypointChanged == null: " + (OnWaypointChanged == null));
//Debug.Log("OnWaypointChanged != null: " + (OnWaypointChanged != null));
}
Waypoints[] GetWaypoints()
{
return GetComponentsInChildren<Waypoints>();
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Vector3 previousWaypoint = Vector3.zero;
foreach (var waypoint in GetWaypoints())
{
Vector3 waypointPosition = waypoint.transform.position;
Gizmos.DrawWireSphere(waypointPosition, .2f);
if (previousWaypoint != Vector3.zero)
Gizmos.DrawLine(previousWaypoint, waypointPosition);
previousWaypoint = waypointPosition;
}
}
}
Here is the EnemyPatrolPoints script
using UnityEngine;
[RequireComponent(typeof(AI_PathFinder))]
public class EnemyPatrolPoints : MonoBehaviour {
[SerializeField]
WaypointController waypointController;
[SerializeField]
float waitTimeMin;
[SerializeField]
float waitTimeMax;
AI_PathFinder pathfinder;
private void Start()
{
waypointController.SetNextWaypoint();
}
private void Awake()
{
pathfinder = GetComponent<AI_PathFinder>();
pathfinder.OnDestinationReached += Pathfinder_OnDestinationReached;
waypointController.OnWaypointChanged += WaypointController_OnWaypointChanged;
}
private void WaypointController_OnWaypointChanged(Waypoints waypoint)
{
pathfinder.SetTarget(waypoint.transform.position);
print("waypoint changed");
}
private void Pathfinder_OnDestinationReached()
{
SealForce_GameManager.Instance.Timer.Add(waypointController.SetNextWaypoint, Random.Range(waitTimeMin, waitTimeMax));
print("destination reached");
}
}
Here is the AI Pathfinder script`
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(NavMeshAgent))]
public class AI_PathFinder : MonoBehaviour
{
[HideInInspector]
public NavMeshAgent agent;
public EnemyPatrolPoints enemyPatrolPoints;
[SerializeField] float distanceRemainingThreshold;
bool m_destinationReached;
bool destinationReached
{
get
{ return m_destinationReached; }
set
{
m_destinationReached = value;
if (m_destinationReached)
{
if (OnDestinationReached != null)
OnDestinationReached();
}
}
}
public event System.Action OnDestinationReached;
void Start()
{
agent = GetComponent<NavMeshAgent>();
//enemyPatrolPoints = GetComponent<EnemyPatrolPoints>();
}
public void SetTarget(Vector3 target)
{
agent.SetDestination(target);
}
void Update()
{
if (destinationReached)
return;
if (agent.remainingDistance < distanceRemainingThreshold)
destinationReached = true;
}
}
The lines
if (agent.remainingDistance < distanceRemainingThreshold)
destinationReached = true;
are never reached as long as destinationReached is true because of
if (destinationReached)
return;
You are setting it to true after the first waypoint is reached and then never reset it to false so your Update is always skipped in the future.
You should add it e.g. to
public void SetTarget(Vector3 target)
{
agent.SetDestination(target);
destinationReached = false;
}

How to hide plane prefab used for plane detection in ARKit using Unity?

I am building an app using ARKit for vertical plane detection.Once the plane is detected I need to turn off plane detection.Even after plane is detected it is still tracking and finding more planes.How to turn off when the plane is detected.
using System;
using System.Collections.Generic;
using UnityEngine.EventSystems;
namespace UnityEngine.XR.iOS
{
public class UnityARHitTestExample : MonoBehaviour
{
public Transform m_HitTransform;
public float maxRayDistance = 30.0f;
public LayerMask collisionLayer = 1 << 10; //ARKitPlane layer
public List<GameObject> Instaobj = new List<GameObject>();
public Transform ForSelect;
int Select;
UnityARCameraManager obj=new UnityARCameraManager();
UnityARGeneratePlane obb=new UnityARGeneratePlane();
bool HitTestWithResultType (ARPoint point, ARHitTestResultType resultTypes)
{
List<ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface ().HitTest (point, resultTypes);
if (hitResults.Count > 0) {
foreach (var hitResult in hitResults) {
Debug.Log ("Got hit!");
obj.Hideplane();
// obb.planePrefab.SetActive(false);
m_HitTransform.position = UnityARMatrixOps.GetPosition (hitResult.worldTransform);
m_HitTransform.rotation = UnityARMatrixOps.GetRotation (hitResult.worldTransform);
Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));
return true;
}
}
return false;
}
// Update is called once per frame
void Update () {
#if UNITY_EDITOR //we will only use this script on the editor side, though there is nothing that would prevent it from working on device
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
//we'll try to hit one of the plane collider gameobjects that were generated by the plugin
//effectively similar to calling HitTest with ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent
if (Physics.Raycast (ray, out hit, maxRayDistance, collisionLayer)) {
//we're going to get the position from the contact point
m_HitTransform.position = hit.point;
Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));
//and the rotation from the transform of the plane collider
m_HitTransform.rotation = hit.transform.rotation;
}
}
#else
if (Input.touchCount > 0 && m_HitTransform != null )
{
var touch = Input.GetTouch(0);
if ((touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) && !EventSystem.current.IsPointerOverGameObject(touch.fingerId))
{
var screenPosition = Camera.main.ScreenToViewportPoint(touch.position);
ARPoint point = new ARPoint {
x = screenPosition.x,
y = screenPosition.y
};
// prioritize reults types
ARHitTestResultType[] resultTypes = {
//ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingGeometry,
ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent,
// if you want to use infinite planes use this:
//ARHitTestResultType.ARHitTestResultTypeExistingPlane,
//ARHitTestResultType.ARHitTestResultTypeEstimatedHorizontalPlane,
//ARHitTestResultType.ARHitTestResultTypeEstimatedVerticalPlane,
//ARHitTestResultType.ARHitTestResultTypeFeaturePoint
};
foreach (ARHitTestResultType resultType in resultTypes)
{
if (HitTestWithResultType (point, resultType))
{
return;
}
}
}
}
#endif
}
}
}
Below is the UnityARCameraManager
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.iOS;
public class UnityARCameraManager : MonoBehaviour {
public Camera m_camera;
private UnityARSessionNativeInterface m_session;
private Material savedClearMaterial;
[Header("AR Config Options")]
public UnityARAlignment startAlignment = UnityARAlignment.UnityARAlignmentGravity;
public UnityARPlaneDetection planeDetection = UnityARPlaneDetection.Horizontal;
public ARReferenceImagesSet detectionImages = null;
public bool getPointCloud = true;
public bool enableLightEstimation = true;
public bool enableAutoFocus = true;
private bool sessionStarted = false;
private ARKitWorldTrackingSessionConfiguration config;
// Use this for initialization
void Start () {
m_session = UnityARSessionNativeInterface.GetARSessionNativeInterface();
Application.targetFrameRate = 60;
//ARKitWorldTrackingSessionConfiguration config = new ARKitWorldTrackingSessionConfiguration();
config = new ARKitWorldTrackingSessionConfiguration();
config.planeDetection = planeDetection;
config.alignment = startAlignment;
config.getPointCloudData = getPointCloud;
config.enableLightEstimation = enableLightEstimation;
config.enableAutoFocus = enableAutoFocus;
if (detectionImages != null) {
config.arResourceGroupName = detectionImages.resourceGroupName;
}
if (config.IsSupported) {
m_session.RunWithConfig (config);
UnityARSessionNativeInterface.ARFrameUpdatedEvent += FirstFrameUpdate;
}
if (m_camera == null) {
m_camera = Camera.main;
}
}
void FirstFrameUpdate(UnityARCamera cam)
{
sessionStarted = true;
UnityARSessionNativeInterface.ARFrameUpdatedEvent -= FirstFrameUpdate;
}
public void SetCamera(Camera newCamera)
{
if (m_camera != null) {
UnityARVideo oldARVideo = m_camera.gameObject.GetComponent<UnityARVideo> ();
if (oldARVideo != null) {
savedClearMaterial = oldARVideo.m_ClearMaterial;
Destroy (oldARVideo);
}
}
SetupNewCamera (newCamera);
}
private void SetupNewCamera(Camera newCamera)
{
m_camera = newCamera;
if (m_camera != null) {
UnityARVideo unityARVideo = m_camera.gameObject.GetComponent<UnityARVideo> ();
if (unityARVideo != null) {
savedClearMaterial = unityARVideo.m_ClearMaterial;
Destroy (unityARVideo);
}
unityARVideo = m_camera.gameObject.AddComponent<UnityARVideo> ();
unityARVideo.m_ClearMaterial = savedClearMaterial;
}
}
// Update is called once per frame
void Update () {
if (m_camera != null && sessionStarted)
{
// JUST WORKS!
Matrix4x4 matrix = m_session.GetCameraPose();
m_camera.transform.localPosition = UnityARMatrixOps.GetPosition(matrix);
m_camera.transform.localRotation = UnityARMatrixOps.GetRotation (matrix);
m_camera.projectionMatrix = m_session.GetCameraProjection ();
}
}
public void Hideplane()
{
config.planeDetection = UnityARPlaneDetection.None;
}
}
I have tried using the Hideplane() method,still the blue plane is showing
I tried this in UnityhittestAR example.I was looking for something like FocusSquare example.Once the plane is detected when we touch the screen the object get placed and no more tracking
Its A temporary solution but it works. In your UnityARKitScene attach a new script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EventHandler : MonoBehaviour {
public GameObject MainPlane;
public GameObject DestroyedPlane;
public GameObject p;
public int Got;
private void Start()
{
Instantiate(p);
}
private void Update()
{
MainPlane = GameObject.Find("Plane");
if(MainPlane!=null){
if(Got==0){
MainPlane.name = "MainPlane";
Got = 1;
}
if(Got==1){
MainPlane = null;
DestroyedPlane = GameObject.Find("Plane");
Destroy(DestroyedPlane);
}
}
}
}

Categories

Resources