现在我正在使用visual basic 2015.我的问题是调试I pin显示错误的变量。而且当前的对象甚至不能获得玩家标签。如果我保持当前对象,我得到正确的变量,但我真的希望固定的变量具有正确的变量。所以我可以更好地了解正在发生的事情。
编辑:我编辑了代码,因此代码与问题发生时的代码不同。它仍然是错误的变量。在Visual Studio 2017中不会发生此问题
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
public class ObjectPlacement : MonoBehaviour
{
//public GameObject[] objects;
public GameObject[] plants; //different plants that can be planted.
private PlaceableObject placeableObject; //Check if other objects are in the way.
public Transform asteroid;
private Transform currentObject; //The object the player is interacting with.
private PlayerInventory inventory; //To get seeds and what tool is being used
private HighlightObject hi; //Change which object that is highlighted
public float clickTimer = 0.2f; //Prevents the player to click to fast and from instantly planting
private float clickTimerReset; //Keeps the value of the original clicktimer
private bool hasPlaced; //prevents double planting
public Animator animController;
private bool clickReady; //Prevents instantly planting
private void Start()
{
clickTimerReset = clickTimer;
inventory = GetComponent<PlayerInventory>();
animController = GetComponent<Animator>();
}
void Update()
{
if (!clickReady) //Prevents the player for planting by accident if the click to fast.
{
clickTimer -= Time.deltaTime;
if (clickTimer < 0)
clickReady = true;
}
Debug.Log("CurrentObject = " + currentObject);
if (currentObject != null && !hasPlaced) //True if a object is currently being placed
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //Coordinates to where the object will be placed.
GetComponent<InteractObject>().SetCurrentObject(currentObject.gameObject); //Sets currentObject in the InteractObject script to show plants area of effect.
currentObject.transform.rotation = transform.rotation; //Can rotate the plant with the players rotation. Quickfix
if ((inventory.currentTool != PlayerInventory.Tool.Free) || Input.GetMouseButtonDown(1)) //Cancels the placement
{
animController.SetTrigger("CancelPlanting");
GetComponent<InteractObject>().SetPlanting(false); //Makes interactive object script able to change currentObject.
hi.SetMaterial(HighlightObject.Type.Normal); //Object set to normal material.
inventory.AddToInventory(currentObject.GetComponent<Seed>().GetSeedType(), 1); //Put seed back to the inventory.
Destroy(currentObject.gameObject);
GetComponent<InteractObject>().SetCurrentObject(null);
Cursor.visible = false;
hasPlaced = true;
currentObject = null;
}
else if ((inventory.GetSelectedSeed() != currentObject.GetComponent<Seed>().seedType) || Input.GetMouseButtonDown(1)) //When changing a seed.
{
animController.SetTrigger("CancelPlanting");
GetComponent<InteractObject>().SetPlanting(false); //Makes interactive object script able to change currentObject.
hi.SetMaterial(HighlightObject.Type.Normal); //Object set to normal material.
inventory.AddToInventory(currentObject.GetComponent<Seed>().GetSeedType(), 1); //Put seed back to the inventory.
Destroy(currentObject.gameObject);
Cursor.visible = false;
GetComponent<InteractObject>().SetCurrentObject(null);
currentObject = null;
hasPlaced = true;
}
Debug.DrawRay(ray.origin, ray.direction * 20, Color.green); //shows the ray in editor window.
if (IsLegalPosition()) //If there is no obstacles in the way, the plant is green and can be planted.
hi.SetMaterial(HighlightObject.Type.Highlight);
else
hi.SetMaterial(HighlightObject.Type.NotAvailable); //There is a obstacle in the way and the plant cannot be planted.
RaycastHit[] hits = Physics.RaycastAll(ray, 20); //Collects all the object the ray hits in a list.
foreach (RaycastHit hit in hits)
{
if (hit.collider.CompareTag("Asteroid"))
{
if (currentObject != null)
currentObject.transform.position = hit.point;
}
if (Input.GetKeyDown(KeyCode.E) || Input.GetMouseButtonDown(0) && clickReady) //plant with a click. Also prevents instaplant
{
if (IsLegalPosition())
{
animController.SetTrigger("PlantingPlant");
currentObject.GetComponent<BasePlant>().Planted(); //Starts the plants growth
currentObject.gameObject.layer = LayerMask.NameToLayer("Interactable"); //changes the layer from IgnoreRaycast to Interactable.
hi.SetMaterial(HighlightObject.Type.Normal);
hasPlaced = true;
hi.SetHologram(false);
hi = null;
currentObject = null;
Cursor.visible = false;
MouseClicked();
break;
}
}
}
}
}
//Checks if there is something in the way
private bool IsLegalPosition()
{
foreach (var item in placeableObject.colliders)
{
if (item.tag == "Plant")
return false;
}
return true;
}
/// <summary>
/// Sets an object in front of the player
/// </summary>
public void UseObject(GameObject _object)
{
if (currentObject == null)
{
if (inventory.useSeed(_object.GetComponent<Seed>().seedType)) //Won't make the object unless the it has the used seed in the inventory
{
hasPlaced = false; //checks that the object hasen't been placed yet
Cursor.visible = true;
animController.SetTrigger("PlacingPlant");
currentObject = ((GameObject)Instantiate(_object)).transform; //The object that is about to be placed
placeableObject = currentObject.GetComponent<PlaceableObject>(); //To check if the object is colliding with other objects.
hi = currentObject.GetComponent<HighlightObject>(); //Makes the code abit tidier. TIDYBOYS ONTZ ONTZ ONTZ
hi.SetHologram(true); //Makes the object turn into a hologram.
MouseClicked();
}
}
}
/// <summary>
/// Starts a timer which prevents an object to be set after a mouseclick.
/// </summary>
public void MouseClicked()
{
clickTimer = clickTimerReset;
clickReady = false;
}
public void SetObject(Seed.Type type)
{
switch (type)
{
case Seed.Type.Normal:
UseObject(plants[0]);
break;
case Seed.Type.Shield:
UseObject(plants[1]);
break;
case Seed.Type.Water:
UseObject(plants[2]);
break;
case Seed.Type.Light:
UseObject(plants[3]);
break;
case Seed.Type.Fruit:
UseObject(plants[4]);
break;
case Seed.Type.None:
return;
default:
break;
}
}
//Incase we ever would need a fixed planting pos again.
//Ray ray = new Ray(); //Creates a new ray
//Vector3 direction = Quaternion.AngleAxis(rayDegree, transform.right) * -transform.up; //Getting the direction of the ray
//Vector3 RayStartPos = transform.up * 2 + transform.forward * 0.2f; //Because vectors is according to world space.
//ray.direction = direction; //Setting the direction to the ray
//ray.origin = transform.position + RayStartPos; //Setting the startpoint of the ray
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
public class ObjectPlacement : MonoBehaviour
{
//public GameObject[] objects;
public GameObject[] plants; //different plants that can be planted.
private PlaceableObject placeableObject; //Check if other objects are in the way.
public Transform asteroid;
private Transform currentObject; //The object the player is interacting with.
private PlayerInventory inventory; //To get seeds and what tool is being used
private HighlightObject hi; //Change which object that is highlighted
public float clickTimer = 0.2f; //Prevents the player to click to fast and from instantly planting
private float clickTimerReset; //Keeps the value of the original clicktimer
private bool hasPlaced; //prevents double planting
public Animator animController;
private bool clickReady; //Prevents instantly planting
private void Start()
{
clickTimerReset = clickTimer;
inventory = GetComponent<PlayerInventory>();
animController = GetComponent<Animator>();
}
void Update()
{
if (!clickReady) //Prevents the player for planting by accident if the click to fast.
{
clickTimer -= Time.deltaTime;
if (clickTimer < 0)
clickReady = true;
}
Debug.Log("CurrentObject = " + currentObject);
if (currentObject != null && !hasPlaced) //True if a object is currently being placed
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //Coordinates to where the object will be placed.
GetComponent<InteractObject>().SetCurrentObject(currentObject.gameObject); //Sets currentObject in the InteractObject script to show plants area of effect.
currentObject.transform.rotation = transform.rotation; //Can rotate the plant with the players rotation. Quickfix
if ((inventory.currentTool != PlayerInventory.Tool.Free) || Input.GetMouseButtonDown(1)) //Cancels the placement
{
animController.SetTrigger("CancelPlanting");
GetComponent<InteractObject>().SetPlanting(false); //Makes interactive object script able to change currentObject.
hi.SetMaterial(HighlightObject.Type.Normal); //Object set to normal material.
inventory.AddToInventory(currentObject.GetComponent<Seed>().GetSeedType(), 1); //Put seed back to the inventory.
Destroy(currentObject.gameObject);
GetComponent<InteractObject>().SetCurrentObject(null);
Cursor.visible = false;
hasPlaced = true;
currentObject = null;
}
else if ((inventory.GetSelectedSeed() != currentObject.GetComponent<Seed>().seedType) || Input.GetMouseButtonDown(1)) //When changing a seed.
{
animController.SetTrigger("CancelPlanting");
GetComponent<InteractObject>().SetPlanting(false); //Makes interactive object script able to change currentObject.
hi.SetMaterial(HighlightObject.Type.Normal); //Object set to normal material.
inventory.AddToInventory(currentObject.GetComponent<Seed>().GetSeedType(), 1); //Put seed back to the inventory.
Destroy(currentObject.gameObject);
Cursor.visible = false;
GetComponent<InteractObject>().SetCurrentObject(null);
currentObject = null;
hasPlaced = true;
}
Debug.DrawRay(ray.origin, ray.direction * 20, Color.green); //shows the ray in editor window.
if (IsLegalPosition()) //If there is no obstacles in the way, the plant is green and can be planted.
hi.SetMaterial(HighlightObject.Type.Highlight);
else
hi.SetMaterial(HighlightObject.Type.NotAvailable); //There is a obstacle in the way and the plant cannot be planted.
RaycastHit[] hits = Physics.RaycastAll(ray, 20); //Collects all the object the ray hits in a list.
foreach (RaycastHit hit in hits)
{
if (hit.collider.CompareTag("Asteroid"))
{
if (currentObject != null)
currentObject.transform.position = hit.point;
}
if (Input.GetKeyDown(KeyCode.E) || Input.GetMouseButtonDown(0) && clickReady) //plant with a click. Also prevents instaplant
{
if (IsLegalPosition())
{
animController.SetTrigger("PlantingPlant");
currentObject.GetComponent<BasePlant>().Planted(); //Starts the plants growth
currentObject.gameObject.layer = LayerMask.NameToLayer("Interactable"); //changes the layer from IgnoreRaycast to Interactable.
hi.SetMaterial(HighlightObject.Type.Normal);
hasPlaced = true;
hi.SetHologram(false);
hi = null;
currentObject = null;
Cursor.visible = false;
MouseClicked();
break;
}
}
}
}
}
//Checks if there is something in the way
private bool IsLegalPosition()
{
foreach (var item in placeableObject.colliders)
{
if (item.tag == "Plant")
return false;
}
return true;
}
/// <summary>
/// Sets an object in front of the player
/// </summary>
public void UseObject(GameObject _object)
{
if (currentObject == null)
{
if (inventory.useSeed(_object.GetComponent<Seed>().seedType)) //Won't make the object unless the it has the used seed in the inventory
{
hasPlaced = false; //checks that the object hasen't been placed yet
Cursor.visible = true;
animController.SetTrigger("PlacingPlant");
currentObject = ((GameObject)Instantiate(_object)).transform; //The object that is about to be placed
placeableObject = currentObject.GetComponent<PlaceableObject>(); //To check if the object is colliding with other objects.
hi = currentObject.GetComponent<HighlightObject>(); //Makes the code abit tidier. TIDYBOYS ONTZ ONTZ ONTZ
hi.SetHologram(true); //Makes the object turn into a hologram.
MouseClicked();
}
}
}
/// <summary>
/// Starts a timer which prevents an object to be set after a mouseclick.
/// </summary>
public void MouseClicked()
{
clickTimer = clickTimerReset;
clickReady = false;
}
public void SetObject(Seed.Type type)
{
switch (type)
{
case Seed.Type.Normal:
UseObject(plants[0]);
break;
case Seed.Type.Shield:
UseObject(plants[1]);
break;
case Seed.Type.Water:
UseObject(plants[2]);
break;
case Seed.Type.Light:
UseObject(plants[3]);
break;
case Seed.Type.Fruit:
UseObject(plants[4]);
break;
case Seed.Type.None:
return;
default:
break;
}
}
//Incase we ever would need a fixed planting pos again.
//Ray ray = new Ray(); //Creates a new ray
//Vector3 direction = Quaternion.AngleAxis(rayDegree, transform.right) * -transform.up; //Getting the direction of the ray
//Vector3 RayStartPos = transform.up * 2 + transform.forward * 0.2f; //Because vectors is according to world space.
//ray.direction = direction; //Setting the direction to the ray
//ray.origin = transform.position + RayStartPos; //Setting the startpoint of the ray
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Assertions;
public class InteractObject : MonoBehaviour
{
public Material radiusMaterial;
public Camera cam; //cam the raycast comes from
public bool clicked; //if an object is clicked
private PlayerInventory inventory; //Get the players inventory.
private bool planting; //To prevent currentObject from changing while planting.
//For interactable zone and editor
[Range(0, 50)]
public float viewRadius; //The radius of the circle that determines the interactable zone
[Range(0, 360)]
public float viewAngle; //The angle between the lines, determining the interactable zone
public LayerMask interactable; //The layerMask we want the code to care about
public List<Collider> interactableObjects = new List<Collider>(); //A list of all interactable objects in range
public GameObject closestObject; //Holds the interactable object closest to the character, if any are in range
[SerializeField]
private GameObject currentObject; //The object the mouse hovers over.
public GameObject mainManager; //Need to access the main manager
private Animator animController;
private HighlightObject tempHighlight;
private HighlightObject.Type oldStatus;
/// <summary>
/// Get all the components needed from scratch
/// </summary>
void Awake()
{
cam = Camera.main;
mainManager = GameObject.FindGameObjectWithTag("Manager");
inventory = GetComponent<PlayerInventory>();
animController = GetComponent<Animator>();
//FIX HERE, TILEPLANT BASED
}
void Update()
{
if (!planting) //Won't change currentObject if the player is planting. Prevents the radius from changing its object.
FindInteractableObjects();
if (Input.GetKeyDown(KeyCode.E) || Input.GetMouseButtonDown(0))
{
UseTool(); //Uses current held tool
}
if (currentObject != null)
{
radiusMaterial.SetVector("_Center", currentObject.transform.position); //The coordinates of the radius center on the ground for the shader.
SetRadius(); //Sets the radius according to plant and plant type.
}
else
HideRadius(); //Sets the radius width to 0 so its invisible.
}
/// <summary>
/// Finds all interactable objects within the interactable area of the player. This area is restricted by the
/// viewRadius and viewAngle variables, and is visible in the unity editor.
/// It then saves these interactable objects in a list that can be accessed throughout the script.
/// </summary>
void FindInteractableObjects()
{
interactableObjects.Clear(); //Clears the list
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //Shoots a ray to the center of the screen from the camera.
RaycastHit[] hits = Physics.RaycastAll(ray, 15); //Saves all the objects the ray hits in a list
Debug.DrawRay(ray.origin, ray.direction * 30f, Color.blue); //Shows a ray in the editor window
foreach (RaycastHit hit in hits) //checks if the hit is a plant
{
if (hit.collider.CompareTag("Plant"))
{
currentObject = hit.collider.gameObject; //Sets current object to a hit.
SetRadius(); //Sets the radius of the effects of the plant
break;
}
}
#region Highlight object
if ((tempHighlight != null) && (tempHighlight.gameObject != currentObject)) //Sets the highlight of the object on change.
{
tempHighlight.SetMaterial(oldStatus); //Sets the old current objects status to what it was.
tempHighlight = currentObject.GetComponent<HighlightObject>(); //Sets th to the newly selected object.
oldStatus = tempHighlight.getStatus(); //Gets the status to change back to when changing the plant.
if (oldStatus == HighlightObject.Type.Highlight) //This is not allowed.
oldStatus = HighlightObject.Type.Normal;
tempHighlight.SetMaterial(HighlightObject.Type.Highlight); //Highlights the newly currentObject.
}
else if (tempHighlight == null && currentObject != null) //Highlights the objects.
{
tempHighlight = currentObject.GetComponent<HighlightObject>(); //sets the currentObject.
oldStatus = tempHighlight.getStatus(); //Saves the old status to change back to
tempHighlight.SetMaterial(HighlightObject.Type.Highlight); //Highlights the currentObject.
}
#endregion
//closestObject = null;
Collider[] interactableObjectsInRange = Physics.OverlapSphere(transform.position, viewRadius, interactable); //KAYERS EXPLAIN
foreach (Collider value in interactableObjectsInRange)
{
Vector3 dirToTarget = value.transform.position - transform.position;
if (Vector3.Angle(transform.forward, dirToTarget) < viewAngle / 2)
interactableObjects.Add(value);
if (value.CompareTag("Seed")) //Picks up a seed
{
Seed.Type _seedtype = value.GetComponent<Seed>().seedType;
inventory.AddToInventory(_seedtype, 1); //Adds the relevant seed to the inventory
Destroy(value.gameObject);
}
else if (value.CompareTag("Collectable")) //Picks up a collectable like Fruit
{
Sellables item = value.GetComponent<Sellables>();
inventory.AddToInventory(item, 1); //Adds collectable to the inventory.
Destroy(value.gameObject);
}
}
}
private void UseTool()
{
switch (inventory.currentTool)
{
case PlayerInventory.Tool.Free:
planting = true;
GetComponent<ObjectPlacement>().SetObject(inventory.GetSelectedSeed()); //Plants a plant with current selected seed
//GetComponent<ObjectPlacement>().MouseClicked(); //Delay on the mouseclick to prevent accidently fast plantig.
break;
case PlayerInventory.Tool.Shovel:
planting = false;
HideRadius(); //Hides the material radius.
if (currentObject != null && currentObject.CompareTag("Plant"))
{
BasePlant SelecetedPlant = currentObject.GetComponent<BasePlant>(); //Makes code prettier
if (SelecetedPlant.fullgrown)
SelecetedPlant.HarvestPlant(1); //Plant drop two seeds since it is fullgrown.
else
{
SelecetedPlant.killPlant(1); //Plants disseappear
inventory.AddToInventory(SelecetedPlant.GetPlantType(), 1); //Drops one seed
}
animController.SetTrigger("Harvesting");
tempHighlight = null; //Removes gameobject to prevent bugs
currentObject = null; // Ditto
}
break;
case PlayerInventory.Tool.Watercan:
{
animController.SetTrigger("Watering");
if (interactableObjects != null)
{
foreach (Collider col in interactableObjects) //Go through the interactable list and and waters the plants.
{
if (col.CompareTag("Plant"))
{
col.gameObject.GetComponent<BasePlant>().WaterPlant(); //Waters the Plant.
}
}
}
HideRadius();
break;
}
default:
break;
}
}
//Adds a seed that is picked up to the inventory.
private void PickUpSeed(Seed.Type sendIn)
{
inventory.AddToInventory(sendIn, 1);
}
/// <summary>
/// Sets the radius for the plants area of effect
/// </summary>
private void SetRadius()
{
Seed.Type sType = currentObject.GetComponent<Seed>().GetSeedType(); //To get the right plant
float _radius = 0; //If the plant does not have a radius it won't be seen.
Color color = Color.blue; //Waterplants natural color since local variables need to be set to something.
bool radiusPlant = true; //True if the selected plant have a radius.
switch (sType) //Sets the type of the radius
{
case Seed.Type.Shield:
radiusMaterial.SetFloat("_RadiusWidth", 0.2f);
_radius = currentObject.GetComponent<ShieldPlant>().radius; //Gets the plants radius.
color = Color.magenta;
break;
case Seed.Type.Water:
radiusMaterial.SetFloat("_RadiusWidth", 0.2f);
_radius = currentObject.GetComponent<WaterPlant>().radius;
break;
case Seed.Type.Light:
radiusMaterial.SetFloat("_RadiusWidth", 0.2f);
_radius = currentObject.GetComponent<LightPlant>().radius;
color = Color.yellow;
break;
default:
radiusMaterial.SetFloat("_RadiusWidth", 0);
radiusPlant = false;
break;
}
if(radiusPlant)
{
radiusMaterial.SetColor("_RadiusColor", color);
radiusMaterial.SetFloat("_Radius", _radius);
}
}
//Hides the circle
private void HideRadius()
{
radiusMaterial.SetFloat("_RadiusWidth", 0);
}
//Sets the planting mode from a differente script : ObjectPlacement
public void SetPlanting(bool set)
{
planting = set;
}
//Sets current object from another script : ObjectPlacement
public void SetCurrentObject(GameObject setObject)
{
currentObject = setObject;
}
}