#archived-code-general
1 messages · Page 122 of 1
Yes
But what if you end the game early, and the script is never destroyed?
I reckon the port never closes
Hmmm
Try closing the port with a context menu function or something, might work
How do I do that
If not, try Portmon and see what app is using it, because that's the only explanation in my opinion.
Create a function that closes the port
Then put the [ContextMenu("name")] attribute above the function
And then you can right click the monobehaviour
and there'll be an option to run the function
and close the port
{
if (dataStream != null && dataStream.IsOpen)
{
dataStream.Close();
Debug.Log("Serial port closed.");
}
}
[ContextMenu("Close Serial Port")]
private void CloseSerialPort()
{
}
``` Something like this? Or have I got it wrong?
Nah, that's good, then just put dataStream.Close(); in the function
{
if (dataStream != null && dataStream.IsOpen)
{
Debug.Log("Serial port closed.");
}
}
[ContextMenu("Close Serial Port")]
private void CloseSerialPort()
{
dataStream.Close();
}```
So like this?
Yep, you should be able to right click the monobehaviour in inspector and click "Close Serial Port"
``` Now I get this
oh
with the same name
You defined two methods with the same parameters and name
If you want to overload a method, you need to make the new one unique by itself
now I saw xD, should I simply rename the second one CloseSerialPort1?
Otherwise you need to give it a different name
What about ContextCloseSerialPort?
{
if (dataStream != null && dataStream.IsOpen)
{
Debug.Log("Serial port closed.");
}
}
[ContextMenu("Close Serial Port")]
private void ContextCloseSerialPort()
{
dataStream.Close();
}``` So like this
So now when I start the project, I should right click and close/?
Or I got it wrong
How exactly
Right click the monobehaviour in the inspector
And click Close Serial port
and that runs the function you wrote
Now the port functions, I do not get that error anymore.
Great! Now you need to make that function run every time you stop running the game
Put now I have like 300 of the same error: ```FormatException: Input string was not in a correct format.
System.Number.ThrowOverflowOrFormatException (System.Boolean overflow, System.String overflowResourceKey) (at <88e4733ac7bc4ae1b496735e6b83bbd3>:0)
System.Number.ParseSingle (System.ReadOnlySpan`1[T] value, System.Globalization.NumberStyles styles, System.Globalization.NumberFormatInfo info) (at <88e4733ac7bc4ae1b496735e6b83bbd3>:0)
System.Single.Parse (System.String s) (at <88e4733ac7bc4ae1b496735e6b83bbd3>:0)
Hand.Update () (at Assets/Script/Hand.cs:28)
Yeah, that's just your string splitting stuff not functioning
Let's fix your port stuff first
And then your string stuff
Yep yep yep
Alright, before you change the script just run that datastream close a couple times
so we're sure its closed
and we can make it run automatically
So basically close the serial port, right?
Yeah, close the serial port when the game quits
There's a function for that, OnApplicationQuit() :D
Get rid of the contextmenu attribute and change the function name to OnApplicationQuit()
That should close the port every time your game stops running, in editor or in build.
{
if (dataStream != null && dataStream.IsOpen)
{
Debug.Log("Serial port closed.");
}
}
//[ContextMenu("Close Serial Port")]
private void OnApplicationQuit()
{
dataStream.Close();
}``` Something like this?
Yeah, commenting it out will work too.
Now then, that's port stuff fixed
String stuff now
Go ahead and just debug log everything you're recieving from the port
so we can see what's going on
Lemme send the code again, maybe it helps you know exactly what the problemo might be : ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
public class Hand : MonoBehaviour
{
public string portName = "COM3";
public int baudRate = 9600;
public Animator handAnimator;
private SerialPort dataStream;
void Start()
{
dataStream = new SerialPort(portName, baudRate);
dataStream.Open();
}
void Update()
{
if (dataStream != null && dataStream.IsOpen)
{
string[] fingerData = dataStream.ReadLine().Split(',');
if (fingerData.Length == 5)
{
float indexValue = float.Parse(fingerData[0]);
float middleValue = float.Parse(fingerData[1]);
float pinkyValue = float.Parse(fingerData[2]);
float ringValue = float.Parse(fingerData[3]);
float thumbValue = float.Parse(fingerData[4]);
handAnimator.SetFloat("Index", indexValue);
handAnimator.SetFloat("Middle", middleValue);
handAnimator.SetFloat("Pinky", pinkyValue);
handAnimator.SetFloat("Ring", ringValue);
handAnimator.SetFloat("Thumb", thumbValue);
}
}
}
void OnDestroy()
{
if (dataStream != null && dataStream.IsOpen)
{
dataStream.Close();
}
}
private void CloseSerialPort()
{
if (dataStream != null && dataStream.IsOpen)
{
Debug.Log("Serial port closed.");
}
}
//[ContextMenu("Close Serial Port")]
private void OnApplicationQuit()
{
dataStream.Close();
}
}```
Nah, each implementation is different, easiest way is to debug log it out
DebugLog the fingerData array
where you had the animation set float stuff
{
Debug.Log(fingerData[0]));
Debug.Log(fingerData[1]));
Debug.Log(fingerData[2]));
Debug.Log(fingerData[3]));
Debug.Log(fingerData[4]));
}``` Something like this?
Welp, seems like the Index finger hardware isn't connected right, but that's a problem for later.
oh thats why then
You're printing the name of the finger too
not just the raw number
so it cant parse it
Yeah
hey guys can anyone familiar with firebase help? i want to make a semi idle game where every second i gain some currency, what would be the best approach to save that currency? im mainly wondering if using OnApplicationQuit is a viable option for saving the game
For saving you really have 2 or 3 main options, the ones I'm familiar with are playerprefs and binary encryption
If you're literally just saving the currency, go for PlayerPrefs
If you're doing something more complex have a look at binary encryption
im using firebases database
Alright, now I only have raw numbers
Ah
Yeah, that should be parsable
try it out with your original code
Alright
also doesnt playerprefs get deleted when i delete the game?
What, delete the game or quit the game?
Delete the game everything gets deleted, binary encryption or not
Unless you save the savefiles in some obscure folder
that doesnt get deleted with the game
(shady, imo)
yea so firebase it is
Can I ask, why are you using firebase for this?
What's the reason behind needing it to persist between game deletes?
i just want to experiment with this trying to release an android game
I don't know If I am doing something wrong, but now whenever I hit play I get this: All compiler errors have to be fixed before you can enter playmode! UnityEditor.SceneView:ShowCompileErrorNotification ()
Have a look at the console, what errors you got?
Ah, makes sense. https://firebase.google.com/docs/database/unity/save-data
Have a look at the docs if you haven't already
And show me what you've got currently
That's the error from the console
That error shows up because you have other errors
currently i got nothing exciting im trying to think how to architect the project and it depends if OnApplicationQuit data saving is a viable option, I already managed to save and retrieve values from the database
For an android game, OnApplicationQuit is a decent idea
I mean, I can't think of anything better
Ohh, now I see what you mean
That's what I get
if i just leave the game and keep it running in the background would that be counted as applicationquit?
I think so, google it rq?
Aight, can you send me your Hand script?
with hatebin
preferably
this time
Thanks, one sec
using
I think that might actually be your only error, at least console based
Damn.. let me try again haha
Now when I start the project I get this: ```UnassignedReferenceException: The variable handAnimator of Hand has not been assigned.
You probably need to assign the handAnimator variable of the Hand script in the inspector.
UnityEngine.Animator.SetFloat (System.String name, System.Single value) (at <d4133d02309b4839805ff06ac3f8d211>:0)
Hand.Update () (at Assets/Script/Hand.cs:35)
okay so it seems specifically for android i should use OnApplicationPause, then again its the only time the save will be called isnt it a bit risky?
You could also do both.
@weary quiver Do you mind sharing a screenshot of your editor? I believe you haven't configured it.
Drag in the animator to the handAnimator slot
What do you mean by configured?
#archived-code-general message please share a screenshot
What editor do you mean? o.o
Your IDE, like Visual Studio or Visual Studio Code
lawd light modfe
xD
Okay so you don't have intellisense
Please configure your !ide before continuing with the issue. It is not configured.
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
I hoped others would notice but I guess not
you think thats enough? is it not risky that maybe something will not be saved in some cases?
It's a school project with a deadline, I have no problem helping this guy for now instead of getting him stuck for hours
I reckon so, try it out
No point in helping with a misconfigured editor
Disagree. This project is really only part unity as I understand it, mostly serial ports. It's definitely a thing that needs to be addressed
though
That's the only thing I have to do?
Then take it up with the moderators. We all expect your editor to be configured in order to receive help, considering it would just waste time otherwise.
You can try pressing "Regenerating project files".
If you press • Visual Studio (Installed manually) it will be explained in detail
Imma do this really quick.
It's only three steps. I see you already set up VS as your external editor, and now you regenerated project files, so you only really need the Unity workload
If you open your Visual Studio Installer and press modify, then it's over here.
It is also explained in that url
Yes thanks for the help!
Hey there, I need to change those exact settings on 550 animation clips.
How would those be accessed and changed by code in the editor (changing the files themselves, not at runtime) ?
They come from .fbx animation files, and import preset won't work for those settings
Can I dynamically edit terrain at runtime?
side note, how can I export multiple animations from one blender file I export as fbx (or from blender in general)
I am currently using the "profile.beginsample" to sample the Update() function in A* and bidirectional A* algorithm. Will that suffice to compare the performance time of both algorithms? Because if so, why is bidirectional A* taking longer than A* when looking at the timeline in the profiling window? Am I interpreting wrongly?
Don't cross post. If you do, delete the prior post.
How do I dynamically edit terrain tho
is there a function i can use
ugh why is the terrains origin on the corner
rotating it is annoying
Ok, this is progress.

A bit big for some reason, idk why. 
I'll add in the other elements first tho.
Rotating the terrain? I dont think that's a thing, is it?
no, but I needed to rotate its parent
which greatly shifted it
I fixed it, just put it under an object that doesn't need to rotate
You edit the TerrainData:
https://docs.unity3d.com/ScriptReference/TerrainData.html
thx
hi everyone , it would be appreciated if someone can help me in my question in the ai channel... thank you*
how can I convert, say, a collision position into a point on the terrain
Please dont advertise your questions on other channels. People who are interested in ai will definitely find your question there and help if they are able to
noted
You can google "unity convert world to terrain position"
The terrain system has been around for ages and these questions have been answered
okay thanks
I'm trying to make rcs thrusters for spaceships
I can do the manual way of setting each thruster when to fire
but is there a way to tell when thy should fire if I want to change the angular rotation for example
like some kind of all in one equation that would tell me that
where I could place the thrusters anywhere on the ship and they would work, kind of like how ksp did it
and also make them balance eachother out
I've been trying to make them balance eacother out but I haven't tested it yet
I know the ideal amount of GC allocation to do per frame is 0, but it seems difficult to actually accomplish. I'm doing 200-300 bytes right now per frame, with a spike up to 10kb when a large task like pathfinding over a complicated structure is done. I have no reference for what a large amount is, and what amount is considered acceptable. Is there anyone here with experience regarding this? I'd love to at least have some reference for what is "a lot"
Anything that does not cause your frames to skip past your target frame rate for device is okey. You need to profile your specific case.
Also it’s probably entirely possible to not generate garbage at all
My pathfind use unsafe at all
Sure but at a certain point I imagine the annoyance of programming in that way outweighs the benefit of not generating a few bytes of garbage
Sure
Still, I don't know if 1kb is a lot or nothing at all
Like I said it depends on your game and target device
its pointless to stick to zero alloc, its enough not to generate high enough amount for a significant spike that is more ms than a frame
If you see lag spikes related to the gc then reduce the amount of garbage
Its all a balancing game
1kb can be much it could be nothing
also gc in editor should be ignored
I guess it would be easier to just program the way I feel is readable for now
The possible allocations of my pathfind are calling task, realloc of stack and minheap, but only the first one is handing by gc i guess
and then go check when I have problems
My pathfinding is creating a whole lot of nodes for the paths that don't work out, and they are then discarded
what does it mean "handling by gc"
task generates about 0.5kb
Could maintain a pool of these objects but that's why I'm not sure if it's worth it
And i can prevent realloc of stack by malloc the whole buffer at the very beginning but i dont what to fo this….
I would basically like for terrain to rise where an object hits it
nothing is seeming to work
terrain has simple api to modify runtime data
you are painting pixels essentially
you have to reuse the visited array by allocate aa additional stack that keep track the nodes explored and clear it after finish pathfind
hmm
where can I find it
"unity terrain api" first link
and this stack can also be reused
ohh I have to "Flush" it
ill send my code
it doesn't seem to be working
public Terrain Water;
//public AudioSource Splash;
public List<Vector3> PushPoint;
// Start is called before the first frame update
void Start()
{
Water = GetComponent<Terrain>();
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision col)
{
Vector3 Pos = ConvertWordCor2TerrCor(col.transform.position);
PushPoint.Add(Pos);
Water.terrainData.SetHeights((int)Pos.x, (int)(Pos.y), new float[1, 200]);
Water.Flush();
}
//Stolen this bit below
private Vector3 ConvertWordCor2TerrCor(Vector3 wordCor)
{
Vector3 vecRet = new Vector3();
Terrain ter = Water;
Vector3 terPosition = ter.transform.position;
vecRet.x = ((wordCor.x - terPosition.x) / ter.terrainData.size.x) * ter.terrainData.alphamapWidth;
vecRet.z = ((wordCor.z - terPosition.z) / ter.terrainData.size.z) * ter.terrainData.alphamapHeight;
return vecRet;
}
i allocate a pool of all (persistent and unsafe) data structure in awake() i need and i reuse them to prevent meaningless allocation in game main loop @river kelp
you can do that without unsafe
Sure, but what kind of value are you getting from that
those i still cannot prevent the allocation due to task....perhaps i have to use job system
I do that for gameobjects because instantiating them is slow
but I'm not sure if it's valuable to me here
btw async is not multithreaded
sorry im being a pest
@static matrix what happens there? nothing?
nothing happens
I think its doing the collsion, let me check
throw in a debug.log
yeah its detecting it
the object hits and the height doesn't seem to change anywhere
The samples are represented as float values ranging from 0 to 1
took that into account?
Does async run exactly once per frame?
like, once it reaches the "Await" it yields until the next frame?
it yields for whatever the yield instruction yields
await wait until the task is finish
if its await for a frame it will wait a frame
I think await means it doesn't run the next thing in the function until the one before it finishes
but im probably not qualified here
Im a questioneer not an answerer
at least in case of UniTask, i didnt work much with raw async
let me try just setting the height to like 200 in a specific point
instead of where the collision happens
you can yield a method that executes right there on the spot, then it wont suspend
yeah the height doesn't change anywhere
async and enumerators are state machines, same mechanics, but raw async is handled by .net, and coroutines/unitask are handled by unity
actually in unity async can also be handled by unity internally
even tho it allocates default task
Water.terrainData.SetHeights((int)Pos.x, (int)(Pos.y), new float[1, 200]);```What is this line supposed to do exactly?
You are assigning an empty heightmap to it
Which is new float[1, 200]
Get/store the heights in an array
Modify that array at the coordinates that you get from your ConvertWordCor2TerrCor method - assuming it is correct
aha
How
ohh wait
its a two dimensional array isnt it
Yeah, the 1, 200 doesn't seem to make sense really :P
thats the position
Nah that creates a new array with dimensions 1x200
ohh
so how do I access the heightmap I dont see a clear var
Either make your own array and store it somewhere or get it with GetHeights
GetHeights
why does it Have GetHeight and GetHeights but not SetHeight and only SetHeights
ugh
okay Ill take a look
You can define what part of the heightmap you are updating
yeah
I have it open
The description too
I dont fully understand it
how are your docs so pretty
ohhz
Hmm I guess dark mode?
In chrome
Gotta save them eyes
I think I slightly get it now?
Like
heights is the area that is being edited?
i can probably use greasemonkey for that
yes
keep a large buffer for the whole map, keep a small buffer for "stamping" changes from-to
Yeah lets say your heightmap is 100x100
If you want to change it all you would do SetHeights(0, 0, myArray) where myArray has dimensions 100, 100
and the dimensions are the dimensions of the terrain?
Or if you want to update a 10x10 chunk of that heightmap, at position 5, 5 you would do SetHeights(5, 5, myArray) where myArray has dimensions 10, 10
Does that make sense?
Not always the same as world space dimensions
Because the heightmap doesn't necessarily have 1 height per unit (meter)
just think of it as pixels
ah
Yeah, it's really just a texture
ahh
hey can i get some help plz, a bunch of stuff in my mouseLook script like sensitivity is increasing and my recoil is completely different from the editor and the game when it has been built.
void LateUpdate()
{
mouseLook = controls.Player.MouseLook.ReadValue<Vector2>(); //Get Mouses Values
//Calculate random recoil
if (Mathf.Abs(upRecoil) > gunDataScript.minRecoilThreshold)
{
upRecoil += gunDataScript.snapiness * Time.deltaTime * ((upRecoil > 0) ? -1 : 1);
}
else upRecoil = 0;
if (Mathf.Abs(sideRecoil) > gunDataScript.minRecoilThreshold)
{
sideRecoil += gunDataScript.snapiness * Time.deltaTime * ((sideRecoil > 0) ? -1 : 1);
}
else sideRecoil = 0;
test.SetText(xRecoil + "/" + sideRecoil);
mouseLook.x += xRecoil;
mouseLook.y += yRecoil;
//Adds sensitivity & adds recoil to the camera
float mouseX = upRecoil + mouseLook.x * mouseSensitivity * Time.deltaTime;
float mouseY = sideRecoil + mouseLook.y * mouseSensitivity * Time.deltaTime;
//Calculats t
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90, 90); //Clamps the Y axis value that way player dont look past head/feet
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f).normalized; //Rotates the Camera
playerBody.Rotate(Vector3.up * mouseX); //Rotates the Player on the X axis
}
public void RecoilFire(float up, float side)
{
upRecoil += Random.Range(-up, up);
sideRecoil += Random.Range(-side, side);
}
}
so
then how do I tell it how much to change it by?
even the grass you pain is also literally a texture
where in the function is that
You put that 0-1 value in the array
oh
OHHHH
var MyArray = new float[30, 30];
MyArray[0, 0] = 1;
Water.terrainData.SetHeights((int)Pos.x, (int)(Pos.y), MyArray);
Like this?
That would change only one position to the max value
yes
but it would change it
The rest of the positions in that 30x30 array are default float value which is 0
yep
So probably not what you want
its closer
how do I edit a lot of the values
ig I can use a for loop but that seems wrong
Hey guys, trying to climb up a rope - works OK with Raycast but when looking away, RC fails and I fall.
At the moment I'm climbing up by projecting my move vector onto the vertical lane of the Rope (Raycast Hit)
Vector3 movement = new Vector3(0, ctx.inputs.moveInput.y, 0);
movement = Vector3.ProjectOnPlane(movement,ctx.RopeRC.normal);
Want to change Raycast for OverlapSphere, but this is giving me a collider.
Is it somehow possible to move alongside a collider?
Does defining a Start() method on a class that inherits from another class that inherits from MonoBehaviour that has a Start() method defined override the inherited class's definition or do both their Start()s execute?
@static matrix Start with having a float[,] heights in your script.
Use heights = terrainData.GetHeights(0, 0, terrainHeightRes, terrainHeightRes) or something like that to populate it
Then modify it
if terrain height is set to 300 and you want 67 units you set the value to Mathf.InverseLerp( 0f, terrainData.heightmapScale.y, 67)
It's maybe not as performant as modifying a certain slice of the terrain but this will get you started
ok tysm
How would I go about drawing a 3d line between 2 points but have the line use 45 degree angles to get to the points, kind of looking like a circuit diagram?
Maybe try snapping the positions on a grid with some algorithm (bresenham?) Then draw lines between those points
Sounds like you should pick the minimum of your x/y/z distances and go that far
Then repeat twice
does anyone know why 2d game is with min scale 1.3x already?
Is this a pixel perfect camera thing?
last question is it possible to make a terrain collider a trigger?
what do you mean?
Doubt you can.
why?
I'm not a 2D expert but are you using a pixel perfect camera
well because water
I noticed you are using it for water is that why
make a mesh inside blender
maybe you can export the terrain as FBX and then reimport it into blender and bakc into unity as mesh collider
@static matrix Why are you using terrain for water though?
because I want dynamic water
like a thing falls into it and theres a splash
but yeah just use a box
Oof, the performance is going to be ass
well thats why im trying to do it with heightmap edits
rather than having 2000 rigidbodies which was my previous solution in 2d
which was very laggy
HDRP has a new water system I think, if you wanna try that
Using terrain for water splashes/waves sounds very inefficient but you can try it
I'm in too deep to migrate to HDRP I think
If it only happens at a certain position then it might be ok
ive tried to do it a couple of times and it never works out
but yeah
maybe ill mess around in a new project just to see how the water works
does unity have cloth physics actually?
It does but I don't guarantee it to be a great solution for this either :P
Does the collider have to match the visuals exactly?
Then you probably want to use a box collider anyway for the collisions
yeah I will
I would make the water effects with a shader (compute shader possibly) but that's a bit more advanced
what did I do oh my god
happens occasionally
I think unity understands that Im out of my current depth and is trying to warn me
unfortunately for my computer I will ignore these omens
sdfhekd I give up for now
Ill make cool water later
Cloth and Water ? wut
the HDRP water is godsent, you're missing out 😛
yeah
Im not doubting that
its that it'll be a big hassle to switch
I might see what it is like
unless you have custom shaders, it should be 1 package u download
switch out the SO/ done
wdym by switch out the SO
what is SO
Scriptable Object
the HDRP/URP are scriptable pipeline
ill give it another try
well you just have to use the converter so the shader goes from URP/BIRP for example to HDRP
indeed
always make a backup/copy project ofc before you do anything. best to practice that too
or use VC(version control)
even better

its cool getting familiar with the community because its usually the same couple of people helping with questions
hey am i suppose to be using Time.deltatime with unitys new input system because when i make a build the mouse sensitivity is super high but when i get rid of it, it feels "normal" but breaks my recoil system.
am i suppose to be using Time.deltatime with unitys new input system
You use Time.deltaTime to convert "per frame" quantities into "per second" quantities. It really depends exactly what we're talking about
The input system isn't really the main question.
If you are reading mouse deltas, you should never be multiplying deltaTime
that goes for both input systems
Old input system may have some magic internal multipliers, so you just might need to adjust your values
my materials died
huh
any idea why?
doesn't sound code related
this was a followup from before
oh
@static matrix it still technically not related to code 😛
well see thats the thing, all my recoil needs to be changed and even when i do change, i get completly different results making it impossible to reference the editor/hard to ajust settings
you can ping fine if I was already in convo with you .
this would go in #💻┃unity-talk or #archived-hdrp
I have not tested if there are any physics , and if you mean Boyancy you could probably just do that with a script.
Unity's Ski Water demo has a script for that
I mean like splashies
I drop item in water it splash
or like theres ripples when you walk
maybe I can just find a good water shader online
any idea to avoid it? 🙄
cant you just make a splash effect spawn particle where you dropped item on "box collider"
thats quite a good idea
I dont know how I could have been so blind
but either way does anyone know a good water shader
okii
not code question
ill figure it out
No idea, I would ask in a more appropriate channel
for example?
#💻┃unity-talk , #🖼️┃2d-tools I dont know but it's not a code question is it
oh, maybe it is not, thanks
I have a question about interface implementations. Am I not allowed to implement or override implementation of a method of an interface inside a child?
public interface ISomeInterface
{
public bool DoSomething() { return false; }
}
public class SomeClass : SomeOtherClass, ISomeInterface
{
// Not Implementing the ISomeInterface methods.
}
public class ThisClass : SomeClass
{
public bool DoSomething() { return true; } // <- Not considered an implementation of the interface that SomeClass, and by extension this one inherits?
}
The original implementation of the interface methods must include the virtual to allow for derived classes to override the methods
The code you posted, however, is invalid. SomeClass does not implement all of the methods of ISomeInterface.
Make it abstract or implement the methods.
Oh wait, I just realized you included an implementation in the interface
I'm a little fuzzy on that. I haven't used it myself yet.
Here's a description of how that works.
uh oh
quick question:
cam.transform.localRotation = Quaternion.Euler(Mathf.Clamp(cam.transform.localRotation.eulerAngles.x, -45f,45f), Mathf.Clamp(cam.transform.localRotation.eulerAngles.y, -45f, 45f), 0);
I'm using this to clamp the rotation of my camera
however the minimum rotation is 0 and when it reaches it it will span back to 0
why is this happening?
clamping euler angles can be very surprising
rotating an object around one axis can change the euler angles on the other axes
Is this a first person camera?
yeah
i would suggest just storing the yaw (left-right rotation) and pitch (up-down rotation) as floats
and then set the camera's local rotation based on those values
it's what I've done in a few different games
public interface ISomeInterface
{
public virtual bool DoSomething() { return false; } // IDE Screams that virtual is a redundant keyword in this context.
}
public class SomeClass : SomeOtherClass, ISomeInterface
{
// Not Implementing the ISomeInterface methods.
}
public class ThisClass : SomeClass
{
public override bool DoSomething() { return true; } // IDE Screams that there's nothing to override.
}
Usually you'd ask a question but relative to just your code alone, what you're writing with is an interface where it's sort of expected that classes interfacing it would implement the methods.
my bad it's a response to this
after modifying from these suggestions
So the original class interfacing the interface would have the virtual member
Your inheriting class would override the member
Interface just forces the class to implement non implemented methods in the interface. The child would need the parent member to be virtual if you're wanting the child class to override the parent's member.
can someone help me please im very new with unity and im trying to make my flint lock push me in the oposit direction i shoot but i cant figure it out (sorry if this is the wrong chat room to send this to im new here)
finally found a good one
(ik not scripting but follow up from before convo ends now)
-transform.forward is backward
Use that as you need
i dont think i understand could you please elaborate
May not be relevant. I misinterpreted you as asking about overriding a method that a parent implemented to satisfy an interface
What I'm trying to achieve is this (from c++)
class Something
{
public:
bool DoSomething() { return false; }
}
class OtherThing : public SomeOtherClass /* <- This class is the MonoBehavior Class in Unity so it needs to be here*/, Something /* <- This would be the interface since c# does not allow multiple class inheritance*/
{
// Do stuff without implementing DoSomething cause I don't need it to be implemented at this level.
}
class CurrentThing : public OtherThing
{
public:
bool DoSomething() override { return true; }
}
Was there anything in particular that you did not understand from what I wrote? Because it should have answered what you're needing.
sorry for the late reply and thx for answering before. now is there any work around i can do if i have to multiply it by Time.delta? because if i get rid of it, it makes my recoil code dependent on framerate
Pretty sure Mouse.delta already makes it frame independent
For the same reason time.delta makes other code frame independent
Well I would like to avoid putting the default implementation inside the top level class. That kinda defeats the point of what I'm showing with the c++ example by using a class that can be reused elsewhere. There will be a lot of methods in that interface adn I don't want to keep redefining all of them inside every class that will implement the interface. The only thing I can think of at this point is to change the interface to a class and the methods to delegates and work from there I guess
Don't make the top level class implement the interface then. Have the child class interface as needed.
i think that maybe the problem with my code, but when i try to separate them and have time.deltatime on the end of my recoil instead, it still seams to make the recoil code frame dependent.
void LateUpdate()
{
mouseLook = controls.Player.MouseLook.ReadValue<Vector2>(); //Get Mouses Values
//Calculates recoil pattern
if (!gunDataScript.allowInvoke)
{
if (!gunDataScript.isAiming)
{
xRecoil = gunDataScript.xRecoilPattern.Evaluate(gunDataScript.bulletsShotInARow);
yRecoil = gunDataScript.yRecoilPattern.Evaluate(gunDataScript.bulletsShotInARow);
upRecoil += gunDataScript.snapiness * Time.deltaTime * ((upRecoil > 0) ? -1 : 1);
sideRecoil += gunDataScript.snapiness * Time.deltaTime * ((sideRecoil > 0) ? -1 : 1);
}
else
{
xRecoil = gunDataScript.xADSRecoilPattern.Evaluate(gunDataScript.bulletsShotInARow);
yRecoil = gunDataScript.yADSRecoilPattern.Evaluate(gunDataScript.bulletsShotInARow);
}
}
else
{
xRecoil = 0;
yRecoil = 0;
upRecoil = 0;
sideRecoil = 0;
}
mouseLook.x += xRecoil;
mouseLook.y += yRecoil;
//Adds sensitivity & adds recoil to the camera
float mouseX = upRecoil + mouseLook.x * mouseSensitivity * Time.deltaTime;
float mouseY = sideRecoil + mouseLook.y * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90, 90); //Clamps the Y axis value that way player dont look past head/feet
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f).normalized; //Rotates the Camera
playerBody.Rotate(Vector3.up * mouseX); //Rotates the Player on the X axis
}
mouse input should not be multiplied by deltaTime
let me go fetch the explainer I wrote recently..
oh it wasn't very long
lol
mouse input is an amount of change, not a rate of change
Yes, so is time.deltaTime
just fix your recoil code which sounds broken in its own right.
it feels weird to just mash recoil and mouse input together into one place
Is there a callback or postprocessor I can use to run code when a ScriptableObject's serialized data changes? I'm using SOs as persistent databases, and they contain some unserialized indexes (dictionaries) that are accessed in edit mode. I'd like to be able to refresh those indexes when the serialized data changes.
you don't "have to" multiply it by deltaTime, that's definitely not correct for mouse deltas
I would separate them.
compute where the player should, logically, be looking, then add the recoil-induced rotation on top
The simple way is to put the camera on a child object of the one you're controlling with your mouse look
so it can recoil independently
oh yeah, that's a good thought
a lot of problems get simpler if you just use two or three objects
yes
lol
scroll down read my posts
You can also try this
https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html
@wide dock @ebon nova and after all that asset db stuff is done and working, i advice moving it out of unity into separate cs project and compile it into a dll, which you drop into unity
so that it keeps running when project fails to compile/load correctly
ugh why do children of an object bend really weirdly
its annoying
like when I rotate it is scales stupidly
non-uniform scale
non-uniform scale
can I turn that off
non-uniform scale
yes, don't non-uniformly-scale anything
non-uniform scale
i.e. don't have scale that isn't all the same value
a scale of [3,1,1] is non-uniform
ill just unparent them on start to solve the issue
When you rotate the child object, that changes how it gets stretched.
since you change how it aligns with the parent's X/Y/Z axes
Right now I'm kinda stuck at just checking out how to just reload the scripts with this, kinda got the base idea of how OnPostprocessAllAssets works
Just one more question for now, you said to "lambda it onto EditorApplication.delayCall", but how exactly do I do it?
For now I just did:
using UnityEditor;
public class CustomAssetPostProcessor : AssetPostprocessor
{
private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
EditorApplication.delayCall += EditorUtility.RequestScriptReload;
}
}
```to check out if script reloading even works this way, but nothing seems to be happening
you want to trigger compilation?
i think theres a different method for that
CompilationPipeline.RequestScriptCompilation();
Yeah, I want to reload the script after saving so that the new enums show up in the inspector
The script is being generated within OnValidate() (for now), I just need to reload it for Unity to notice it
the script is a cs file?
yes
you are modifying it with File ?
did you set it dirty after changes?
the MonoScript
AssetDatabase.Refresh and others
I'm modyfing it with StreamWriter
anyway its IO, unity detects changes on focus, otherwise you need to call https://docs.unity3d.com/ScriptReference/AssetDatabase.Refresh.html
scripts are also simply monitored for changes, and imported as MonoScript
but the changes are detected only at specific points
Ok, this worked perfectly, thanks!
I was working on a project and suddenly the methods for the camera class were not avalible in a script. I am referencing the proper namespaces and have regenerated project files.
Hi guys please help me, with this 4 build errors
Can I change a particlesystem to be just trails?
why audio mixer is not working in build? in editor I can change the sound volume with a slider but the same slider does nothing after building; the mixer setFloat seems to not work at all in build
Nevermind I fixed it
did you read player logs?
how can I access them? do I need to make development build for that?
thanks, I'll check them in a sec
how do i make a joint connect two rigidbodies who do move with one another but whose rotations are independent of one another, like an axle with two wheels that are allowed to spin freely of one another.
@ashen yoke NullReferenceException: Object reference not set to an instance of an object
at SoundOptions.OnEnable () [0x00012] in <6307d21e8f5740a1896857d764429186>:0
yeah expected something like that
how come the reference is null only in build?
and why onEnable? The script is attached as component to an object
so I made a game with playerprefs, i made the build and on other computer it works fine but not on mine, how ?
Is like it works fine on the editor and if other people download it it works, but on my computer it does not run right
you're gonna want to check #854851968446365696 for what to include when asking a question as "does not run right" in incredibly vague and provides no information
yeah my bad let me explain better
private void Start()
{
if(!PlayerPrefs.HasKey("level"))
{
PlayerPrefs.SetInt("level", 1);
}
}
public void sceneLoader()
{
if(PlayerPrefs.GetInt("level") == 1)
{
SceneManager.LoadScene(1);
}
else
{
SceneManager.LoadScene(2);
}
}
when you start the game the first time this happens, in pratice if there is no level variable is set to 1, and then if you press the button it loads scene one
on every computer scene 1 is loaded but on mine scene 2 is loaded for some reason
clear the playerprefs keys on your computer and try again
i uploaded the game on itch and i donloaded it so it should be cleared
that does not clear the playerprefs
where are they stored ?
if you're on a windows machine they are stored in the registry
i thought they were stored in the file with all the unity fiels,
use https://docs.unity3d.com/ScriptReference/PlayerPrefs.DeleteAll.html on your computer
they are completely independent of the game files
huh
so even if you remove and install the game the saves stay
didn't knew that thanks
yes
Hi folks. I'm trying to figure out a way how to use multiple NavMeshAgents to move to single target(wall in this case). When I use target position, it obviously not working well, since all the agents coming from relatively same direction and pushing each other. I am in a process of creating a logic that will provide a unique position near the target, so all the agents will have their own “spot”
Is there some easy way to do it, that I am missing something obvious here?
does anyone know how to change this top field?
oh, I have discovered it
RectTransform rt = typingField.GetComponent<RectTransform>();
rt.offsetMax = new Vector2(rt.offsetMax.x, -166f); // sets to 166
Hey, I want the Ray i'm shooting out to ignore a layer I choose. How would I do that? I tried looking it up but I didnt get any working answers
Use a layermask
should have been the first thing that comes up when you search for that
does anyone know how to get line height of TMP_InputField or TextMeshPro?
I just need my InputField's height to be equal 3 text lines by changing its top and bottom values I guess
there should be something like ComputeSize(string)
does it reffer to me?
yes
Oh i was using it wrong the whole time Thanks though!
yes, https://docs.unity3d.com/Packages/com.unity.addressables@1.20/api/UnityEngine.ResourceManagement.ResourceLocations.ILocationSizeData.ComputeSize.html, I wonder how this can help me 🤔
it can help you if you notice me saying "something like"
because i remember using it but i dont remember the exact name
For the following scene, my A* had an avg exec time of 0.10ms while bidirectional A* at 0.20ms. Is this normal? And it’s been consistent no matter where I put. Am I analysing it wrongly?
Enemy Sript
public class enemy : MonoBehaviour
{
public int health = 100;
public GameObject effect;
public GameObject player;
// Start is called before the first frame update
public Vector3 playerPos;
public Animator anim;
public gameManager gm;
void Start(){
gm = GameObject.FindGameObjectWithTag("GM").GetComponent<gameManager>();
}
void Update() {
transform.position = Vector3.MoveTowards(transform.position, player.transform.position, 2 *Time.deltaTime);
}
public void takeDamage(int dmg){
anim.SetTrigger("damageTrigger");
health -= dmg;
if(health <= 0){
die();
}
}
void die(){
//Instantiate(effect, transform.position, Quaternion.identity);
Destroy(gm.copy);
}
}
Enemy Spawn
public class gameManager : MonoBehaviour
{
private int waveNumber = 0;
public int enemiesAmount = 0;
public GameObject blob;
public Camera cam;
public Text wave;
public GameObject copy;
// Use this for initialization
void Start () {
cam = Camera.main;
enemiesAmount = 0;
}
// Update is called once per frame
void Update () {
wave.text = "Wave: "+ waveNumber;
float width = cam.orthographicSize * cam.aspect + 1;
float height = cam.orthographicSize + 1; // now they spawn just outside
if (enemiesAmount==0) {
waveNumber++;
for (int i = 0; i < waveNumber; i++) {
copy = Instantiate(blob, new Vector3(cam.transform.position.x + Random.Range(-width, width),3,cam.transform.position.z+height+Random.Range(10,30)),Quaternion.identity);
enemiesAmount++;
}
}
}
}
this is the error i am getting
i think its something with deleting the intantiate clone
idk if i did that right
where are lines 38 and 32?
then gm.copy is null
release mode? cold start? at those 0.01ms number this can be just overhead from basic allocations and whatnot
and bidirectional should have double amount of structures
i also do think that GO with tag GM does not exist
should i not store the instatiate in a variable then
you should check whether you have GO with tag GM
also I don't think it's a good tag
on large maps paths taking 30, 100, 300ms are acceptable sometimes
you need GO with correct tag and correct script on it
copy is null
also use FindObjectOfType<>
they don't need I guess
better practice, generally
I am trying to make some precise movement but the transform component keeps values as floats and therefore can get to some random stuff. Can I force it to show and return values to one decimal point?
0.3 is not a number that exists in binary (floating point representation) unfortunately
so no
this is just floating point precision, you shouldnt see a single noticeable difference in your game because of this
if you are comparison positions to another object, try using Mathf.Approximately or tell us what this is for
If you're trying to do grid based movement you should use integer grid coordinates at the lowest level
converting to floating point only at the final moment for presentation purposes
Vector3 comparison actually uses 0.00001 distance threshold already
If Equals did too, it would probably mess up hashsets and dictionaries somehow
If I were to see the effects, what should the grid size be? I tried 80x80, with a semi complex environment. A* was faster by triple.
I still can't understand how NullReferenceException: Object reference not set to an instance of an object at SoundOptions.Start () [0x00015] in <8fd0a29f74f54040b4f1f0ce22d43c56>:0 is thrown only in build; if someone can help me please
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
public class SoundOptions : MonoBehaviour
{
[SerializeField] private AudioMixer m_audioMixer;
[SerializeField] private Slider[] sliders;
private void Start()
{
m_audioMixer.SetFloat("masterVolume", GameManager.Instance.Settings.m_masterVolume / 1.25f - 80);
m_audioMixer.SetFloat("musicVolume", GameManager.Instance.Settings.m_musicVolume / 1.25f - 80);
m_audioMixer.SetFloat("effectsVolume", GameManager.Instance.Settings.m_effectsVolume / 1.25f - 80);
sliders[0].value = GameManager.Instance.Settings.m_masterVolume;
sliders[1].value = GameManager.Instance.Settings.m_musicVolume;
sliders[2].value = GameManager.Instance.Settings.m_effectsVolume;
}
private void OnEnable()
{
sliders[0].value = GameManager.Instance.Settings.m_masterVolume;
sliders[1].value = GameManager.Instance.Settings.m_musicVolume;
sliders[2].value = GameManager.Instance.Settings.m_effectsVolume;
}
public void OnMasterVolumeChange(float value)
{
GameManager.Instance.Settings.m_masterVolume = (int)value;
m_audioMixer.SetFloat("masterVolume", GameManager.Instance.Settings.m_masterVolume / 1.25f - 80);
}
public void OnMusicVolumeChange(float value)
{
GameManager.Instance.Settings.m_musicVolume = (int)value;
m_audioMixer.SetFloat("musicVolume", GameManager.Instance.Settings.m_musicVolume / 1.25f - 80);
}
public void OnEffectsVolumeChange(float value)
{
GameManager.Instance.Settings.m_effectsVolume = (int)value;
m_audioMixer.SetFloat("effectsVolume", GameManager.Instance.Settings.m_effectsVolume / 1.25f - 80);
}
}
this is the code, basically I get data from GameManager and initialize option sliders and mixer volumes
in editor everything is fie
fine*
Using the input system, you use events to activate methods, since it is like that, what is the best way to add parameters to the methods called
For example say i wanted to pass a variable to the method Walk...
Input.Move.Walk.started += Walk;
I saw something on the forums about using lambda, but am not sure how that works considering you have to provide the input action callbacks aswell
@ me if you know
chances are GameManager.Instance is null due to a script execution order problem
1000s
the crosshair in my game is a simple png, but in the editor when i run my game, the crosshair gets blurry, even though compression is set to none, and it is imported as sprite (2d and ui). what can i do about this? thanks!
Filter mode in the texture's import settings.
Not a code question btw.
it can't be; it's lazy instantiated; also it's on top of the list in script order execution
thanks! didn't really know what kind of question it is tbh
show the GameManager class
So Debug.log is your friend, there is not a lot to chose from
I commented all the acceses to gameManager, onenable is emtpy so is start and I get NullReferenceException: Object reference not set to an instance of an object
SoundOptions.OnEnable () (at Assets/Scripts/Options/SoundOptions.cs:25)
wtf
it looks like Unity has some problems calling OnEnable and Start on this component
and line 25 is?.
Please dont rush into blaming Unity
is the beginning of onenable
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
public class SoundOptions : MonoBehaviour
{
[SerializeField] private AudioMixer m_audioMixer;
[SerializeField] private Slider[] sliders;
private void Start()
{
//m_audioMixer.SetFloat("masterVolume", GameManager.Instance.Settings.m_masterVolume / 1.25f - 80);
//m_audioMixer.SetFloat("musicVolume", GameManager.Instance.Settings.m_musicVolume / 1.25f - 80);
//m_audioMixer.SetFloat("effectsVolume", GameManager.Instance.Settings.m_effectsVolume / 1.25f - 80);
//sliders[0].value = GameManager.Instance.Settings.m_masterVolume;
//sliders[1].value = GameManager.Instance.Settings.m_musicVolume;
//sliders[2].value = GameManager.Instance.Settings.m_effectsVolume;
}
private void OnEnable()
{
//sliders[0].value = GameManager.Instance.Settings.m_masterVolume;
//sliders[1].value = GameManager.Instance.Settings.m_musicVolume;
//sliders[2].value = GameManager.Instance.Settings.m_effectsVolume;
}
public void OnMasterVolumeChange(float value)
{
GameManager.Instance.Settings.m_masterVolume = (int)value;
m_audioMixer.SetFloat("masterVolume", GameManager.Instance.Settings.m_masterVolume / 1.25f - 80);
}
public void OnMusicVolumeChange(float value)
{
GameManager.Instance.Settings.m_musicVolume = (int)value;
m_audioMixer.SetFloat("musicVolume", GameManager.Instance.Settings.m_musicVolume / 1.25f - 80);
}
public void OnEffectsVolumeChange(float value)
{
GameManager.Instance.Settings.m_effectsVolume = (int)value;
m_audioMixer.SetFloat("effectsVolume", GameManager.Instance.Settings.m_effectsVolume / 1.25f - 80);
}
}
do you expect me to count lines?
if you are getting an error in OnEnable then you did not save your changes
when it's a build specific error that doesn't show in editor at all it kind of is
no it isn't, it's you not understanding the difference between editor and builds
but hey, a few simple Debug.Logs and you will KNOW what the problem is, I leave it up to you
at SoundOptions.OnMasterVolumeChange (System.Single value) [0x0000a] in <43a3666bdfb54c90a83941094ae13e78>:0
at UnityEngine.Events.InvokableCall`1[T1].Invoke (T1 args0) [0x00010] in <52c27bfe78c147d5b895bd1a8cd729d7>:0
at UnityEngine.Events.UnityEvent`1[T0].Invoke (T0 arg0) [0x00025] in <52c27bfe78c147d5b895bd1a8cd729d7>:0
at UnityEngine.UI.Slider.Set (System.Single input, System.Boolean sendCallback) [0x0002d] in <c4cd81d65a5748d7876a01a2c95fc090>:0
at UnityEngine.UI.Slider.set_value (System.Single value) [0x00000] in <c4cd81d65a5748d7876a01a2c95fc090>:0
at UnityEngine.UI.Slider.set_normalizedValue (System.Single value) [0x00013] in <c4cd81d65a5748d7876a01a2c95fc090>:0
at UnityEngine.UI.Slider.UpdateDrag (UnityEngine.EventSystems.PointerEventData eventData, UnityEngine.Camera cam) [0x000be] in <c4cd81d65a5748d7876a01a2c95fc090>:0
at UnityEngine.UI.Slider.OnDrag (UnityEngine.EventSystems.PointerEventData eventData) [0x00012] in <c4cd81d65a5748d7876a01a2c95fc090>:0
at UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IDragHandler handler, UnityEngine.EventSystems.BaseEventData eventData) [0x00007] in <c4cd81d65a5748d7876a01a2c95fc090>:0
at UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) [0x00067] in <c4cd81d65a5748d7876a01a2c95fc090>:0 ``` this is the full stack trace btw
I would if it would happen in editor and not in build ... with a weird stack trace like this
and I still dont know what line that is on
but that is build, it's dll stack trace
Do yourself a favour, put some debugs in your code then look in the player.log
I just did that: "ENTERING ON ENABLE SOUNDOPTIONS!
NullReferenceException: Object reference not set to an instance of an object
at SoundOptions.OnEnable () [0x0001c] in <cb314a39dc294bd3ad7271933b89bc62>:0
ENTERING START SOUNDOPTIONS!
NullReferenceException: Object reference not set to an instance of an object
at SoundOptions.Start () [0x0001f] in <cb314a39dc294bd3ad7271933b89bc62>:0 "
do you not know how to debug?
seems like it's breaking from the audio mixer
I've got a situation where "time" can be non-linear (you can scrub through playback to get the state of something at a specific time) and I want an animation to be starting at some point in time after when it should start. I have the timestamp of when an animation should have started, I have the current time stamp, and I have the name of the animation that should be playing at this point in the timeline. I need to play that animation at the proper normalized time to where it would be at that timestamp. Easy enough to find what that normalized time is, it's the InverseLerp of the current timestamp minus the start time from the clip's duration.
Only problem: How do I get the duration of a clip by name? I can get the current state info, but entering the state, getting the info, then getting the length from that in order to play that animation again from a new start point seems clunky and awful, and usually with Animator controls that means I'm doing something the hard way.
are there any chances mixer group references are not loaded in builds?
debug which object is null
finally found it, thanks for the tip, but is kinda cryptic so far; basically the game manager wasn't initializing properly cuz of this: The process cannot access the file 'C:\Users\saita\AppData\LocalLow\SaiTatter\BEARing\Player.log' because it is being used by another process.
and I know the culprit; I was deleteing everything from persistent folder when initialising the game manager (was working on save files and wanted clean ones each time)
and editor doesnt write player.log
Then you have more than one build running at once
only build so yep...
I try to delete it but it's opened by the unity engine so that's a lock; damn shady one
at least I can exclude all files but that one so it should be okay; sorry for wasting your time; I think I wasted all my day with this 😦
I have a monobehaviour that is linked a scriptableobject with the settings pertaining to it. should I cache the values of those settings, or is there no performance penalty in addressing the attrs of the mentioned SO?
A single instance of the SO is created at runtime, the idea is you read from that single instance, so technically it's pretty performative as is
Right, so I am trying to make a camera rotate around a pivot point when the middle mouse button is held. The horizontal rotation works fine, but I am having a hard time with the vertical rotation. It keeps flipping around, or other methods will lock it once it gets to the top/bottom. Something just isn't click for me right now. Any advice?
public class SceneCamera : MonoBehaviour
{
[SerializeField] private Vector3 _pivot;
[SerializeField] private float _speed = 1;
private Vector3 _startMousePosition;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse2))
{
_startMousePosition = Input.mousePosition;
}
if (Input.GetKey(KeyCode.Mouse2))
{
Vector3 delta = Input.mousePosition - _startMousePosition;
Quaternion rot = Quaternion.Euler(-delta.y * _speed, delta.x * _speed, 0);
transform.position = rot * transform.position + _pivot;
transform.LookAt(_pivot);
_startMousePosition = Input.mousePosition;
}
}
}
I've done that by parenting the camera to a "RotateX" object, then parent that to a "RotateY" object. So just have different transforms for each rotation. (Set the camera's local z pos to something positive like 5) That makes it easier to work with imo.
I could I guess, but that feels like a dirty hack and not at all the 'correct' way to do it.
if you dont wanna do the gameobject approach i suggest using this method https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html
to tilt the view (up and down) rotate around a horizontal axis (like transform.right) and to pan the view (left and right) rotate the view around a vertical axis (like transform.up)
Already tried that. That causes it to lock at the top/bottom
even with rotatearound?
With just rotating on the x axis, this is what ya get
Vector3 delta = Input.mousePosition - _startMousePosition;
transform.RotateAround(_pivot, Vector3.right, -delta.y * _speed);
transform.LookAt(_pivot);
_startMousePosition = Input.mousePosition;
i think the issue is with transform.lookat
when you dont include an "up" vector for lookAt it assumes world as being up
but im assuming you want your camera to be able to go upside down so that's a no-no
Oooh, I bet you are right!
Hmm, what direction should I provide then?
i dont think you need to use lookAt at all
i think rotateAround preserves the direction towards the pivot
hey, i can post code if necessary but im hoping this is a common issue with a simple fix
my character can double jump but sometimes if i mash the jump button, it performs a third jump before the code is able to update the number of jumps left.
even if i add some kinda bool like readyToJump that ensures the number of jumps decreases before a jump is performed, im able to sneak a third jump in.
how do i fix this :]
it probably has something to do with how you're checking for the ground
so how are you doing that?
oh hmm. so you think there might be a frame or two where im jumping but still touching the ground so it resets the number of jumps?
yes exactly, but it probably depends on how you're doing it. raycasts would likely lead to this issue
im debugging now to check
Welp... that was it. It now rotates relative to the rotation of the camera, which not what I want. But I will mess around with it and probably figure it out. Thank you for the help 🙂
no problem
gaaaaaaaah and now of course since i've asked for help, im unable to replicate the error
aha! yep. i think its triggering the reset as i leave the ground
so this is how im currently grounding.
@light rock how would you recommend i do the grounding check to avoid this issue?
void Update()
{
temp.Clear();
foreach (Transform child in transform)
{
temp.Add(child.gameObject);
}
if (temp != saved)
{
saved = temp;
saveFile();
}
}
Why is the function saveFile is just called when I turn on the game or when script are reloded ?
If i change temp saved changes too but save file is not called
I just checked and the if statement is not called when i change temp, EDIt it does but it does not call a debug.log
what is temp and saved even? you havent provided any context for what this is supposed to do
because saved and temp are referring to the same instance of the List after the first time this code runs
is like unity does not know that I updated the lists ?
ohh i think i got it, if i say saved = temp know saved is just temp ?
you did update the list, sure. but that doesn't mean that saved suddenly isn't the same list still. List<T> is a reference type. this means when you do something like saved = temp; then both variables point to the same instance in memory until you assign a new list to either of the variables.
all you are doing here is checking whether they are the same instance then if they are not you make them the same instance and call your SaveFile method
so i need to check the elements
they are literally the same list in memory
when i fixed this issue for myself when i had it, i actually didnt change the way i did ground-checks. instead, i just keep track of the time in-between jumps, and i dont let the player jump within like .2 seconds of the last jump
Ah that's a good idea. I assume you have some kind of jump buffer so that if the player jumps in those .2 seconds, it still registers the input and jumps when the time is up?
that might feel pretty awkward for the user if you buffer the jump like that
I just have a cooldown from the last jump, regardless if they actually got off the ground due to ceilings or whatever else
Hm fair enough. I'll test out a couple of options. Thanks for the help, all
the jump cooldown alone really should get rid of most double jump issues at least. Within the 0.2 seconds your character shouldnt still be grounded
or whatever timer u set it to. Its really just a few frames that itll be grounded
"entity_number": 6,
"name": "filter-inserter",
"position": {
"x": 3.5,
"y": 2.5
},
"direction": 6,
I am trying to get something like this using json utility
public class StructuresJSON
{
public int entity_number;
public string name;
public class position
{
public double x;
public double y;
}
public int direction;
}
is this the right way ? if yes how do i declare the class positon?
Because once i declared the new structure i would do json utility to jason of the new class
Right way to do what?
to get the json output that i showed
https://www.youtube.com/watch?v=4oRVMCRCvN0&t=246s
This tutorial shows how to get a json string, he uses a class, then si converted to json with json utilities, but it does not show how to do nested values like the position values, so iam improvising a bit but i don't know how to do it
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
✅ Unity Basics for Beginners Playlist: https://www.youtube.com/playlist?list=PLzDRvYVwl53vxdAPq8OznBAdjf0eeiipT
In this video we're going to learn what is JSON, how its formatted and how we can use it in Unity to easi...
You can test this really easily just by creating a json string. No need to create and write to file
yes but how
StructuresJSON structureJSON = new StructuresJSON();
structureJSON.entity_number = i;
structureJSON.name = structures[i].tag;
i decleared the first values, but how do i declare the rest?
public class position
{
public double x;
public double y;
}
This, i am not suire nesting classes is the way to go
because structuresJSON.position.x does not work, but if i declare the class positon as a new class it will not be all in one string
you're going to have to instantiate the position, otherwise what would u be setting as x and y
a position, but thats not the problem
what do you mean it wont all be in one string also
have u printed out the actual json string?
i think we are not understanding each other
"entities": [
[
{
"entity_number": 1,
"name": "centrifuge",
"position": {
"x": 1.5,
"y": 1.5
},
"recipe": "kovarex-enrichment-process"
},
{
"entity_number": 2,
"name": "steel-chest",
"position": {
"x": 4.5,
"y": 0.5
}
},
]
how do i create a class that when i run it trught JsonUtility.ToJson(entitites); i get the json string above
i get the aprt where you make a class, but my problem is that how do i decleare a key that has more keys inside
is there any studio accept remote student for internship? no salary needed.
like entitites is an array, but is not an int or a string, is an array of many things, do i make a class and then declare tha array as a class
i don't think this is the place to ask this
also why would you want to do job for free
I'm still a student. do you know site where can I find?
i think your structuresJson needs a
public position p;
then i make a class position and declare it as int x int y ?
that would make sence
I only have experience and web development, I'm making a big decision to pursue game development.
linked in i guess
i am a student too
if you want to do some game developement you should start doing game jam and try to get a name for youself
at least thats what seems a good idea, working for some one else looks sad
at least when you start
where can I look for game jam?
Can I private message you if you dont mind? I ask a few question just handful one
i am busy but you can ask some where else in the discord
go on the discussion channels like #💻┃unity-talk or #🕹️┃game-jams
Is there a way to have something like
using System;
using UnityEngine;
[Serializable]
public class ExampleClass
{
[SerializeField] private int test;
}
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(ExampleClass))]
public class ExampleClassEditor : Editor
{
public override void OnInspectorGUI()
{
[...]
}
}
using UnityEngine;
[RequireComponent(typeof(GameEventObject))]
public class ExampleBehaviour : MonoBehaviour
{
[SerializeField] private ExampleClass example;
}
This doesn't seem to work in the editor, which suggests the custom editors only work for monobehaviours?
Is there some other way to control how a class will display on the unity editor?
Use a PropertyDrawer
Thanks, this is leading me down the right path 👍
After banging my against the whole for another 45 minutes... I got nothing.
This rotates the camera and makes it look at the pivot. But it does the rotation around the current axis, not the world global axis.
Which means if you rotate 45 on the X, then 90 on the Y, the Z rotation of the camera is going to be rotated and everything will be titled.
transform.RotateAround(_pivot, Vector3.up, delta.x * _speed);
transform.RotateAround(_pivot, Vector3.right, -delta.y * _speed);
I know how to rotate the position around the pivot. The hard part is getting the rotation so that when you go past 90 degrees on the x (past looking down at the pivot) the camera will go upside down instead of flipping around.
So if anyone has some direction, I would love to hear it!
@mild orbit gimme 2 sec, maybe one of my repos has this
doesn't look like it, lemme whip something up rl quick for you
it's a lot easier to not use euler angles
in general for coding, is it better to just "make something now" and fix it later
or is it better to slow the momentum of your project, but do something properly the first time
I just need something that works and works well, idc if it needs refactor at some point
depends on your intent I guess
The answer to most question like these is it depends on what you are making, really you should be the judge of this. Are u making something thats fundamental to the rest of your program, with everything building ontop of this low level code? If so, you probably dont want to refactor this and a billion other things. You should plan on the structure to minimize changes, but obviously there will be some.
If this is just like moving the player, then just get something working
The former in general. Refactoring, rewriting, and throwing code away is the norm. You should and will do it many many times over the course of your project. Code is never really complete, and the needs of the project will always be evolving anyway
it's the first pieces of code in my project
creating player movement
creating interfaces I'll use later
etc.
I find that I keep on coding these things
and I spend a lot of time trying to make it the best I can
cause I dont' want performance issues down the road
but it kills my momentum
you'll refactor it anyways
I don't get things done
I also find that I keep on trying to do things in order to get more performance for diminshing returns when I don't need to
@mild orbit here you go
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraPivot : MonoBehaviour
{
// Start is called before the first frame update
public Vector3 pivot;
public Vector2 sensitivity = Vector2.one;
public float cameraDistance = 10;
float pitch = -30;
float yaw = 0;
void Start() {
}
private void Update() {
if (Input.GetMouseButton(0))
{
pitch += Input.GetAxis("Mouse Y") * sensitivity.y;
yaw += Input.GetAxis("Mouse X") * sensitivity.x;
}
var horRot = Quaternion.AngleAxis(yaw, Vector3.up);
var verRot = Quaternion.AngleAxis(pitch, Vector3.right);
var dir = horRot * verRot * Vector3.forward;
var cameraUp = Vector3.Cross( horRot * Vector3.left, dir );
transform.position = pivot + dir * cameraDistance;
transform.LookAt( pivot, cameraUp );
}
}
Oooh! My hero! Thank you Mad 🤩
Ahh I see, it is that Cross to get the Camera up
yeh, you can also do it using the rotations to set the camera rotation directly but this is conceptually more straightforward bc if you just apply them directly the camera will be facing outward instead of inwards
so you need to use the inverse rotations instead which is a bit awkward
Yeah, there was a number of ways I had tried doing it. When using LookAt, I kept getting stuck at what/how to pass as the up.
I even tried doing it with like a quaterion delta and adding it to the main rotation. It was ugly... and didn't work
yah part of that was using euler angles, since you don't have a decomposed rotation to work with
I much prefer working with angleaxis instead of euler when doing any camera rotation stuff
first person or 3rd person
Huh, good to know. Thanks! Quaternions are definitely a weak area for me, and vector math is a semi close second 😅
So I really appreciate the help!
public bool checkOverlaps(GameObject structure)
{
string save = File.ReadAllText(Application.dataPath + "/save.json");
SaveJSON saveJSON = JsonUtility.FromJson<SaveJSON>(save);
for(int i = 0; i<structures.Count; i++)
{
if (checkOverlap(saveJSON.entities[i], structure))
{
return true;
}
}
return false;
}
#region variables for checkOverlap
double x1;
double x2;
double y1;
double y2;
double minX;
double minY;
#endregion
public bool checkOverlap(Entities structure1, GameObject strucure2)
{
for (int i = 0; i < prefabs.Length; i++)
{
if(structure1.name == prefabs[i].tag)
{
x1 = prefabs[i].GetComponent<snapToGrid>().x;
y1 = prefabs[i].GetComponent<snapToGrid>().y;
break;
}
}
x2 = strucure2.GetComponent<snapToGrid>().x;
y2 = strucure2.GetComponent<snapToGrid>().y;
//if they are rotated sideways we need to invert x and y aka width and height
if (structure1.direction % 2 != 0)
{
(x1, y1) = (y1, x1);
}
if(strucure2.GetComponent<RotateSprite>().rotation % 2 != 0)
{
(x2, y2) = (y2, x2);
}
//we are getting the minimum distance between the two object by summing half of theyr lenght in both axis
minX = x1 / 2 + x2 / 2;
minY = y1 / 2 + y2 /2;
//check if the distance X and Y are equal or greater than the minimun distance it will return true
if (Mathf.Abs((float)structure1.position.x - strucure2.transform.position.x) >= minX || Mathf.Abs((float)structure1.position.y - strucure2.transform.position.y) >= minY)
{
return false;
}
return true;
}
so in my game there is a grid where i spawn game object, i don't want to have them be one on top of the other, so i wrote a script that saves the location of each object in a json, then i read it and check if there are any collision.
How can i optimize it ?
after around 500 objects it starts to get really slow
one thing i thoght would be to get objects just close to the one i am cheking
Firstly, not calling GetComponent repeatedly on the same object inside a hot path will do a bunch
Then you've got a bunch of string comparisons in there too for some vague reasons
which one ?
structure1.name == prefabs[i].tag
that one is used because i store the name of the structure and i need to find the prefab with stored the value X and Y for that structure
is bad ?
Why dont you find some places to cache all the x and y of prefabs and using a dictionary to O(1) fetch
like instead of taking it from the prefab just store the x and y some were and use those?
would be smart
at that point i could just check what tag does the object 2 has and use the x and y from the prefab there
I find AngleAxis to be a fairly intuitive way to work with quaternions without needing to grok the underlying mechanics too deep
for some reason raycast.point is being returned -.4 units off, does anyone know why
Off from what, I have no clue what that image is supposed to be showing
im trying to make an fov effect with raycast and a custom mesh but the vertecies are off
You'd have to explain better what that means and what it would be like for "the vertices" to be "right"
nvm
I have a question about physics ...
in the following image the tennis ball falls and the bowling ball goes up and to the right (BLACK ARROWS) ... I want it to go up and to the right (RED ARROW)
how can I make this happen? I am using rigidbody2d to handle physics not C#
with physics its going to go to the right, because your seesaw is rotating and has angular velocity in that direction. If you want it to go to the left, then you'll have to addforce in that direction through script
ok thank you
I want to cache the scenes that will be loaded with SceneManager.loadsceneasync in the background. I want to load and resume when necessary, but I don't have much experience with async operations, can you give an example?
Hello i think i encountered a bug or something with Unity, i am making a script to test how certain values change but for some reason the inspector randomly breaks and only displays 1 value or 3 of the actual 8 it should display
anyone know how to fix this?
show the script
These are some of the values it should also display but it doesn't
[Header("Properties")]
public float Radius = 0.5f;
[Header("Calculated Values")]
public float Load = 2452.5f;
public Vector2 LocalVelocity = Vector3.zero;
public float AngularVelocity = 0.0f;
public float LNSlip = 0.0f;
public float LTSlip = 0.0f;
they are public and nothing special is done with them
it just weirdly breaks randomly
these errors also show up sometimes entering playmode but this is code from Unity itself
sheesh
this is in the 2022.3.0f1 LTS also
maybe try deleting Library folder
will do, does this version already use toolkit for ui instead of what they had first?
not sure. i still use 2021
if it does i think they switched too soon it seems not production ready because in 2021 it works fine
i see there is a 1f1 version now though maybe it is fixed in that one
how do I install AI package manager?
Do you prefer to put all your different runtime objects in one list with base interface/abstract to save?
or separate them in different lists based on their types?
public class WorldPersistentData
{
public List<DataPersistenceObject> Buildings;
public List<DataPersistenceObject> Items;
//...
}
public class WorldPersistentData
{
public List<DataPersistenceObject> Objects;
}
2dir vs A*
that's according to what you need I would say
though I think first one looks more readable and convenient
Hello everyone !
I am using Visual studio Code with the Unity Editor.
When I have an unused variable declared in a class outside of a function, I get a warning.
How do I get the same type of warning for a variable declared inside a function ?
(I have no doubt there should be a setting for vs code for hits)
you mean this?
yeap
is VS Code set as your default editor in Unity?
I think so (it's the one when I double-click on a C# file in unity)
(also if possible in the unity console to have the list of 100 unused variable directly :p )
yes the first one is more readable but maybe less flexible, more code
Edit -> Preferences -> External Tools -> External Script Editor
yeah yeah, it's vscode
yes, it's according to what you need. I also believe that Item is not the same as the Building, but if it does not make difference in your game, you can just combine'em
idk then, it works in Visual Studio, not Visual Studio Code (haven't used this one for Unity)
@urban marsh maybe you consider installing Unity Technologies extension? (I guess)
Yes, definitely, item is completely different from building.
I have decided to save all of them as a base data structure.
When loading and instantiate
// Loading
foreach(var data in persistenceObjects){
var asset = data.GetComponent<Asset>();
var assetDef = _assetCollection.Get(asset.Id);
var gameObject = Instantiate(assetDef.Prefab);
gameObject.GetComponent<Loader>().Load(data);
}
too many vars💀
Because, if I separate them (in my example Building from Item), I need to have different spawn system for each.
foreach(var data in persistenceBuildings){
}
foreach(var data in persistenceItems){
}
" This extension is deprecated as it is no longer being maintained.".
I have it still installed, but get a warning since last month.
last updated more than a year ago.
just void with parameter
I did not get
what is persistenceObjects?
type
List<DataPersistenceObject>, right?
public abstract class PersistenceObject : MonoBehaviour
{
[SerializeField] [Required] private Entity _entity;
private IDataPersistence[] _dataPersistenceArray;
private void Start()
{
_dataPersistenceArray = GetComponentsInChildren<IDataPersistence>();
WorldStorageSystem.Instance.Saving += OnSaving;
}
private void OnDestroy()
{
WorldStorageSystem.Instance.Saving -= OnSaving;
}
private void OnSaving()
{
WorldStorageSystem.Instance.Add(this);
}
public void LoadData(DataPersistenceObject dataObject)
{
for (var i = 0; i < _dataPersistenceArray.Length; i++)
{
_dataPersistenceArray[i].LoadData(dataObject);
}
}
public void SaveData(WorldPersistentData worldData)
{
var persistenceObject = new DataPersistenceObject();
persistenceObject.Id = _entity.InstanceId;
for (var i = 0; i < _dataPersistenceArray.Length; i++)
{
_dataPersistenceArray[i].SaveData(persistenceObject);
}
DoSaveData(persistenceObject, worldData);
}
public abstract void DoSaveData(DataPersistenceObject data, WorldPersistentData worldData);
}
A base monobehaviour which handles save/load for that gameobject
no, persistenceObjects is List<PersistenceObject>?
yes
@earnest gazelle
private void LoadSmth(List<DataPersistenceObject> persistenceObjects)
{
persistenceObjects.ForEach(data =>
{
Asset asset = data.GetComponent<Asset>();
int assetDef = _assetCollection.Get(asset.Id);
GameObject newObject = Instantiate(assetDef.Prefab);
newObject.GetComponent<Loader>().Load(data);
});
}
have you tried it already?
?!
that's answer for this, actually
yeap, I have it installed.
even before or I did not understand correctly?
I have it since I begun using vscode with unity, a yeaar ago.
always had warning for unused vars declared outside of functions, never for vars inside them.
You said it is better to separate them.
In this code, all are in one list.
@gray mural the thing you linked is outdated.
searching aroudn on google, I found a few prople with similar problems, but the settings interface changed in the last few years, and I can not find the same settings :/
no, I haven't sad that it is better
I have said that it's according to you
and if you would like to seperate them, then you should make a method for them
you have said that you did not get it, so I made you an example
yes, I have sent a link for VS, sorry
I think you should either ignore it or consider installing new editor e. g. Visual Studio
I have an question on how to have the flashlight in my players hand rotate correctly with my player. Currently, when my player rotates the flashlight follows my player but stays in the same rotation, for example, if I turn 180 I see the back end of my flashlight. Am I suppose to have an empty transform in the flashlight, and then have the flashlight rotate on the horizontal axis inline with my camera's rotation?
or is their an easier way to implement this?
Easiest way is if your flashlight is a child of the player
it is a child of the player
it rotates but not correctly
the flashlight is a prefab I made in blender
I think thats why its not working correctly
Prefab or not it should still rotate along with the parent
Try manually rotating it and seeing what happens
Have you worked with message pack?
Hey, Why can't I serialize/deserialize it using message pack?
[MessagePackObject]
public class DataPersistenceObject
{
[Key(0)] public Guid Id;
[Key(1)] public Dictionary<int, IData> Components { get; } = new();
[MessagePackObject]
public class WorldPersistentData
{
[Key(0)] public List<DataPersistenceObject> Objects;
}
I have added implemented types
[MessagePack.Union(0, typeof())]
public interface IData
{
}
and it is message pack resolver
static WorldStorage()
{
var resolver = MessagePack.Resolvers.CompositeResolver.Create(
// resolver custom types first
BuiltinResolver.Instance,
MessagePack.Unity.UnityResolver.Instance,
// finally use standard resolver
StandardResolver.Instance
);
MessagePackSerializerOptions = new MessagePackSerializerOptions(resolver);
MessagePackSerializerOptions = MessagePackSerializerOptions.WithCompression(MessagePackCompression.Lz4Block);
}
Components is empty [0] when loading/deserializing.
Objects (list) is OK. It has some elements in
Guid is OK as well.
The problem is Dictionary
Dictionary<int, IData> Components
Does anyone here have experience with Morpeh ECS?
WHY DOES VS CODE DELETE WORDS AFTER IT WHEN IT AUTOFILLS
im actually going insane nothing ive tried works
ive tried reinstalling and that doesnt do anything either
hello, i`m try to invoke event by his name but i get error:
TargetException: Object does not match target type.
code with getting event:
GetType().GetEvent(eventName).EventHandlerType.GetMethod("Invoke").Invoke(???, new object[] { whatHeDone , whoItDone });
im not sure what i need instead of ??? (previous that i used:
GetType().GetEvent(eventName).EventHandlerType.GetType())
(P.S. GetMethod("Invoke") is successfully get func.)
record it with obs
why are you using reflection?
Guys im trying to make a raycast with multiple raycast but it looks wrong this is what I mean, How I can fix this? This is a custom wheel collider im not trying to use unity wheel collider. https://cdn.discordapp.com/attachments/831185804746555448/1117047530581147699/image.png This is the code where the angle is calculated https://pastebin.com/tTuqdD6N
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Your rotation axis is wrong (If transform.forward is where I think it is). You need to rotate on the vector right which is the x axis.
Quaternion rayRotation = Quaternion.Euler( 0f, angle, 0f ); => Quaternion rayRotation = Quaternion.Euler( angle, 0f, 0f );
well i don`t know any other possibility to do that. That was first that i found
The ??? is the instance of the object you want to invoke on.
indeed, since non-static methods must be invoked on a specific object
The object on which to invoke the method or constructor. If a method is static, this argument is ignored. If a constructor is static, this argument must be null or an instance of the class that defines the constructor.
However, you should ask yourself if you really need reflection. It is most of the time a bad idea. (Without trying to be rude; Even more for people that do not understand fundamental concept)
It is also not performant.
indeed, since the compiler can't just produce IL that calls a method
it has to go find it at runtime
For the following scene, my A* had an avg exec time of 0.10ms while bidirectional A* at 0.20ms. Is this normal? And it’s been consistent no matter where I put. Am I analysing it wrongly? The grid size is 30x30. And node radius of 0.5.
why dont you have a look at your search space?
well i want to invoke event by its name.
I think that might be faster to code but when i read your thoughts about reflection i dont think that a great idea.
btw i started do this because i want to let users somehow make a addons for game in the future
the node radius doesnt matter how your algorithm runs, your algorithm only consider V and E
so it takes exactly as long if you set the destination to be only one tile away?
i haven't implemented that in a while
it feels like it should be pruning paths that are longer than the best-known path
Hello !
I come back with the same question as before, hoping hat there are different people this time and maybe somebody knows the answer :
I use vs-code with Unity.
vs-code is my default unity editor.
When I implement a script and I have an unused var declared outside a function, I will get a warning in the Unity Console, telling me it is unused.
When I have an unused variable inside a function, I do not get a warning anywhere : it is not highlighted in vs-code, and there is no warning in the Unity console.
Do you guys know a way to get a warning somewhere ?
Start by using a real ide.
i will get variable is declared but never used if i declare it inside the function but not the reverse case
ofc i use vs code
I get warnings when I have unused local variables in VSCode.
Perhaps you can show an example.
protected int pif;
protected void func() {
int paf;
int pouf = 2;
pouf += 1;
}```
I get warnings for pif and paf, but nothing for pouf, even though it is a useless variable.
It is used in some sense.
that's not a local variable
it's a field
and it's a protected field, so a derived class could use it
there is nothing wrong here
oh, I misread your code
🫠
can that int ever be visible to anyone else?
declaration of pif should not be warned...
sounds like something is up with your linting rules
it's possible to disable specific messages. perhaps you have done that?
Is it an unused variable warning?
If I have done that, it wa *s not on purpose, and I don't know how to undo that. I would like to undo that.
i suspect there are many ways to do this...but in my case, I've done that exclusively via .editorconfig
[**.cs]
dotnet_diagnostic.IDE0017.severity = none
dotnet_diagnostic.IDE0060.severity = none
dotnet_diagnostic.IDE0051.severity = none
dotnet_diagnostic.CS8524.severity = none
dotnet_diagnostic.UNT0028.severity = none
dotnet_diagnostic.CS0282.severity = none
i can't remember what these are
I want the unused variable warning (or any warning, really, for the poufvariable)
Meaning? Just the visualisation of the grid and the path taken like the first pic?
Where am I suppoed to look for the .editorconfig file ?
Looking for it in hte project gives me weird results
Someone else suggested that bidirec won’t show it’s effects until 1000ms, implying mine’s too small?
"search space", shows all explored nodes
it would probably be in the project root
if it's not obviously there, then it's probably not the issue
by draw a line from parent to children or simply log the number
i prefer first way
wait -- what is your actual question?
is it about bidirectional search being slower?
Does somebody know what method executes when the new line is entered in TMP_InputField?
(without using "\n", just when there is too much text)
no .editorconfig at the project root. a simple .vsconfig, but it does not contain anything like that.
Yeah. Upon invoking the Update() of both algorithms, in the same indoor navigation environment.
i would not be surprised if it only outperformed the regular search with a sufficieintly large problem size
i thought you were just asking if that 0.1-ish millisecond runtime was expected
Hi. This is driving me crazy. If I have a Plane with transform.position center and transform.forward normal, how do I project the vectors V1 and V2 onto the plane and then calculate the angle between the two vectors projected onto the plane? Thank you.
This doesn't work, the drawn rays are wrong:
Vector3 projectedPoint1 = Vector3.ProjectOnPlane(prevhitpoint.Value, transform.forward);
Vector3 projectedPoint2 = Vector3.ProjectOnPlane(hit.point, transform.forward);
float angle = Vector3.SignedAngle(projectedPoint1 - transform.position, projectedPoint2 - transform.position, transform.up);
Debug.DrawRay(transform.position, projectedPoint1 - transform.position, Color.red);
Debug.DrawRay(transform.position, projectedPoint2 - transform.position, Color.green);
ProjectOnPlane removes the component of the vector that points in the directional of the normal
what you're doing feels off here
feels like you should be subtracting the position of the plane from the two points before the projection
for a trivial example: imagine the plane is at [0,0,1] and the point is at [0,0,1], with a normal vector of [0,0,1]
actually, hmm, that might work out correctly..
You can also express the position of the vector in function of the plane then remove the Y coordinate.
ah, by just converting from world to local space?
Kinda.
i need a whiteboard for this lol
But using probably https://docs.unity3d.com/ScriptReference/Matrix4x4.LookAt.html