How to move an object in Unity - unity3d

Hello guys I try to make a city building game the idea is very simple actually Instantiate an Building and move them with mouse after that hit the place button and place.
The issue is if the collider of a another building completely encloses the collider of the building that I am built I can't move new building.
I can probably explain better with pictures.
Issue 1
The first picture my new building you can see collider limits and the second one my old building that I already placed. I Understand the problem but I can not solve it.
And here it is my object drag code
private void OnMouseDrag()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, 1000f,(1 << LayerMask.NameToLayer("Ground"))))
{
Debug.Log(hitInfo.transform.name);
transform.position = SnapToGrid(hitInfo.point);
}
}
private Vector3Int SnapToGrid(Vector3 pos)
{
Vector3 tempPos = pos;
Vector3Int snappedPos;
snappedPos = new Vector3Int(Mathf.RoundToInt(tempPos.x), Mathf.RoundToInt(tempPos.y), Mathf.RoundToInt(tempPos.z));
return snappedPos;
}
Thanks for the help in advance

If I got your question right, I believe that you can solve the problem by enableing the "Is Trigger" option of the previously placed buildings colliders at the moment that a new building is being moved around. Enableing this option in an object makes it so other objects can pass trought it when collision happens.

Related

İn Unity Photon Network , Learn who did the bullet come from?

I make a game using photon network . 2 actors are shooting at each other and when the bullet is formed on the stage I want to know who the bullet came from. I can send player id in bullet Instantiate and I can find player in for loop but i don't think it's true.
Is there better than this method?
Code
void Shoot()
{
var part = GetComponentInChildren<ParticleSystem>();
part.Play();
float angle = cc.isFacingRight ? 0f : 180f;
GameObject gameob = PhotonNetwork.Instantiate("Bullet", firingPoint.position, Quaternion.Euler(new Vector3(0f, 0f, angle)),0, null);
}
You can simply use photonView.Owner, since the bullet is a networked object. Alternatively, you can use photonView.IsMine to check if the client running the check owns the bullet, instead of comparing owners.
(The photonView instance comes from assuming your bullet script extends MonoBehaviourPun instead of MonoBehaviour)

Checking raycast hit on tagged collider

I'm trying to make a shooting game and I wanted to check if an enemy is hit using a raycast. Here is the code:
void CheckForShooting()
{
Vector3 mousePos = Input.mousePosition;
RaycastHit2D bulletCheck = Physics2D.Raycast(gunPoint.position,Camera.main.ScreenToWorldPoint(mousePos), gunRange);
Debug.DrawLine(gunPoint.position,Camera.main.ScreenToWorldPoint(mousePos),Color.white);
if(Input.GetButtonDown("Fire1"))
{
if (bulletCheck.collider.tag =="Enemy")
{
print("Hit");
}
}
}
However, even if the raycast is right on top the red enemy the console doesn't print "Hit" and I get the error "NullReferenceException: Object reference not set to an instance of an object", the line that is getting this error is this one bulletCheck.collider.tag =="Enemy".
Here is a ss:
Screenshot]
You need to make a raycast everytime you click the Fire1
Look at this official unity site: https://learn.unity.com/tutorial/let-s-try-shooting-with-raycasts# its explained how to shoot with raycasts.
I wish i could help you directly but i haven't entered Unity in over a year. I hope this helps but for such simple questions its faster to make a google search in my opinion
You just need to check if collider you were supposed to hit is null or not (if it was actually hit). You shoot the ray and expect it to always hit the target in your current code. Just check:
if(bulletCheck.collider != null)
and the code will only run if there was a hit. Only then you can check what was hit.
Also follow the advice and learn about NullReferenceException, it is the most common and basic exception, also one of the easiest to solve.

Updating values in a component in instantiated gameobject in unity

Hi i have a Robot Prefab, with a NPC script that is linked to dialogue sentences.
I am retrieving the information about dialogues (using a loader script) from a server API, and then instantiating both the robot gameobject and the sentences. For example for instantiating the gameobject:
GameObject newObject = GameObject.Instantiate(Resources.Load("prefabs/" + item.gameObject.name) as GameObject, parentProps);
newObject.transform.localPosition = new Vector3(loaded.x, loaded.y, loaded.z);
newObject.transform.localEulerAngles = new Vector3(0, 90f, 0);
However, i do not know how to access the dialogue and update it. Could someone tell me how to update the instantiated value of the sentences here (marked it with red arrows on the image below)?
May be a basic question, but am new. Thanks!
You can create a public function in Npc class and call it after you instantiated it.
GameObject newObject = GameObject.Instantiate(Resources.Load("prefabs/" + item.gameObject.name) as GameObject, parentProps);
newObject.transform.localPosition = new Vector3(loaded.x, loaded.y, loaded.z);
newObject.transform.localEulerAngles = new Vector3(0, 90f, 0);
newObject.GetComponent<Npc>().UpdateDialog();
On your Robot GameObject use GetComponent to get the NPC script object. Then you are able to modify the values. Make sure that the visibility of your variables is either public or has getters/setters.

How to stop NavMeshAgent separating from Animator?

I am working on a research project that uses a NavMeshAgent. I currently have a very simple scene where an agent is spawn at the start, walks through an "entrance" trigger collider, an "exit" trigger collider, then ultimately collides with a "destroyer" trigger collider with a script that ends the scene. Nothing complex, no physics collisions should be occurring.
I've been running some simulations both in the editor and in -batchmode -nographics via an executable that logs a basic runtime statistic when the scene ends. I found that in both the Unity editor and the CLI execution that occasionally the scene's execution time would spike. I finally caught what was happening in action- the NavMeshAgent component was becoming detached from my agent and floating out in front of it.
In this picture you can see the two colliders on the agent (one very small through his body for physics and one larger one for his "personal space",) the exit trigger collider (the giant red box on the right,) and floating between the two is a capsule-shaped NavMeshAgent component.
I used this unity page detailing how to use NavMeshAgents with animators, but after recreating their recommended setup, I am still having the issue.
Does anyone have any solutions for anchoring the NavMeshAgent to the agent itself?
I met exactly the same problem, where making the NavMeshAgent component a child and setting the NavMeshAgent's local position in every frame solved the problem.
private NavMeshAgent agent;
void Awake()
{
agent = gameObject.GetComponentInChildren<NavMeshAgent>();
anim = gameObject.GetComponent<Animator> ();
}
private void Update()
{
agent.transform.localPosition = Vector3.zero;
// todo:
// set animator
}
void OnAnimatorMove ()
{
// Update position to agent position
transform.position = agent.nextPosition;
}
For those of you who stumbled here, but for whom the accepted answer did not work. Make sure that navMeshAgent.updatePosition is set to true or that it is not changed within a script. This could be the cause of the separation.
NavMeshAgent navMeshAgent;
// This may cause the agent to separate
navMeshAgent.updatePosition = false;
// This will make sure it is synced
navMeshAgent.updatePosition = true;
This works as of version 2022.1 of the Unity API. Here are the docs for the function : https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent-updatePosition.html

unity3d OnMouseDown function

I am new to Unity3D. I am trying to do a simple thing. But not able to do this. I have a .obj file which is a 3d key file. I do the followings:
Import this key (to assets) in unity3D
Add this key to scene (from assets to hierarchy)
Add a script to this key
Add the OnMouseDown() function to this script as follows -
void OnMouseDown()
{
Debug.Log ("clicked...");
}
But when I click the key no message is showing in console. Please tell me what is the problem?
make sure the gameobject is not at layer "Ignore Raycast"
Use the following inside your update function to see raycasting is working fine.
void Update () {
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit)) {
Debug.Log ("Name = " + hit.collider.name);
Debug.Log ("Tag = " + hit.collider.tag);
Debug.Log ("Hit Point = " + hit.point);
Debug.Log ("Object position = " + hit.collider.gameObject.transform.position);
Debug.Log ("--------------");
}
}
}
The OnMouseDown and it's related functions are all actually older systems. The newer system to use for this is the event system.
Specifically to get mouse clicks you would implement this interface in a class:
http://docs.unity3d.com/460/Documentation/ScriptReference/EventSystems.EventTriggerType.PointerClick.html
But there is actually an easier way to do it without code.
Using this component:
http://docs.unity3d.com/ScriptReference/EventSystems.EventTrigger.html
You can then visually forward the mouse click event to something else.
If you don't fully follow what I have said so far, the thing to really start at is learning the UI system. You can find video tutorials here:
http://unity3d.com/learn/tutorials/modules/beginner/ui/ui-canvas
And just to make it clear, the UI system is not just for UI. The UI system runs off an EventSystem which is what you want to use to forward input events to any object 3D or 2D in the entire scene. The UI tutorials will explain the usage of that EventSystem.
You need to assign a collider to the 3d object if you want to fire it with OnMouseDown:
OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider.
This event is sent to all scripts of the Collider or GUIElement.
You can also do like by override click function
public override void OnPointerClick(PointerEventData data)
{
Debug.Log("OnPointerClick called.");
}