#archived-code-general
1 messages · Page 24 of 1
if the value is in the dict, then it has a key . . .
you're just comparing the wrong thing, that's all . . .
right, there isn't a dict.ContainsValue() iirc
there is .ContainsValue()
worse performance than a key check
yes, there is . . .
doesnt give the key, if you need that as well then you'd need do the ContainsValue manually
uhh, just google: dictioanry c#, click on microsoft link, click methods on left-side scroll bar and search through all methods . . .
(

)
I was googling the actual question and not just dictionary c# which was the issue
always google what type or class you are using. you'll get the actual link to the class (type) and all of its members . . .
If you're going to use it backwards more, you can make two dictionaries with the key-value pairs swapped and act on both at the same time
good to know thanks
I think I'll stay with my foreach loop...just have to store the values I want to change and wait until Im outside the loop to modify the dictionary
hmm
I wonder if I just throw a break if it wont be mad at me (it was mad at my modifying EquippedList while doing foreach on it)
foreach (var items in EquippedList)
{
if(items.Value == item)
{
tmpList.Add(item);
EquippedList[items.Key] = null;
break;
}
}
if I have a break here it will break the loop and not the if statement right?
break only acts on loop constructs, so yeah
Depending on your code editor if you click on break to put the editing cursor on it, it'll also highlight the loop it acts on
(VS22, was also the case for VS19)
foreach (var items in EquippedList)
{
if(items.Value != item) continue;
tmpList.Add(item);
EquippedList[items.Key] = null;
break;
}
Can also remove the nesting if you find that more readable
☝️ reverse this to exit early and remove the scope . . .
that makes sense
for some reason I thought using continues like that was bad practice or something
I find the version with continue way less readable
Adds complexity on where the execution flows
i'm the opposite lol
it's like asking for a flavor and someone telling you what they do have instead of a simple yes or no. so always exit early to avoid that conversation . . .
fair enough
is there any way that when the game is running and you change code everything doesn't break and you have to re-click play?
I assume not but figure I ask 😄
nope, Unity doesnt support hot reload
Hey! I am having a world of trouble spawning an equipped weapon|item into the characters hand at the correct orientation and position. I would love some advice on the topic please.
I have tried setting a weapon slot empty gameObject in the palm of the player as well as setting an empty gameObject on the grip of the weapon to perhaps attach it that way but I can't seem to get the rotation right and I really don't want to using hardcoded values as I will have more than one weapon and some are 2 handed as well.
2d?
3D sorry
unfortunate, I could kind of help you if it was 2d lol
All good
I have a tile map collider on a tile map made out of rule tiles. Somehow I set it so only the tiles on the edge got the collider and I can't figure out how, does anyone know what setting this is?
like this
super easy to do with an empty GameObject that is properly positioned/rotated
public Transform theEmpty;
var instance = Instantiate(myPrefab, theEmpty.position, theEmpty.rotation, theEmpty);```
How can i detect a change in value.
For example a character is set to lerp to an object and i want an animation play only when he is moving
Do you care to elaborate. theEmpty.pos & theEmptyRot will be the palm GO correct?
theEmpty would be an empty object that is a child of the palm and oriented properly (or if the palm itself is the empty you want to use, sure)
ah, like this I assume
sure
so the position and or rotation is dependend on in my case where I put the WeaponSlot. I need to just play with the empty gameObject to find the right position in the palm and right rotation
yep
🥳 Thank you .
Unity does support this. There are certain requirements that must be met for it to work related to serialization of game state during the hot load of the updated assembly. These notes are old but still relevant: https://gist.github.com/cobbpg/a74c8a5359554eb3daa5
tryBackButton = root.Q<Button>("tryBackButton");
if (tryBackButton == null)
{
Debug.Log("backbutton null");
}
tryBackButton.clicked += GoBack;
``````cs
void GoBack()
{
//MainMenu.instance.CloseMe(root);
root.pickingMode = PickingMode.Ignore;
root.style.display = DisplayStyle.None;
Debug.Log("backclicked");
}```
am I missing something obvious here?
the button isn't clicking/doing the GoBack
just call/invoke the event manually . . .
add a log when clicked is invoked to see if it actually runs . . .
I've got the debug.log set inside of GoBack...which isn't firign
so yes, atm its not clicking
not sure if I set something up wrong or wacky type or ui toolkit being dumb
that checks if the button is null, not if the event was actually fired . . .
I dont quite follow how I would do it otherwise?
I have a debug to see if its null(its not) then another debug for the event that fires when its clicked
What is the purpose of using Strategy pattern instead of simply using implementers of the corresponding interface? In other words, why create the Context class?
figured it out anyway, stupid UI toolkit stuff
If you want to manually trigger the even on a specific UI element and you have the reference, you can invoke that directly (the exact call will depend on what event and ui type you are using). If you want a general way to fake input and mimic what the event system is doing, what you found on google is correct but would take a bit more setup. It's how input modules work.
I have an object that I want to move in a spiral pattern outward while maintaining the same linear speed. How would I approach this?
Math
Can someone explain to me why local variables are useful? Isn't it always going to me more efficient for the computer to declare them as regular fields?
For loop would be one example
But even for for loops isn't it still better to declare them properly at the top of the script?
i feel like they just encourage lazy coding
Not really then a variable would have to stay in the memory
And you’d also have to manually reset the non-local variable
And even if there is a performance difference, it’s practically non-existent
witch c# does automatically right
Unless you keep doing a GetComponent and store that in a local or smth then it is
For a non-local? Of course not
for a local*
I said non-local on here
But for a local yeah, cuz it gets redefined
Which is why it’s good for for loops
Im just thinking, cause each time you create a local var in the update function, you are really allocating and deallocating memory every frame, when you could have just allocated it once when the program started and ended
ah gotcha
It’s not a big deal really
I’d

If you want to know more
each field adds memory to the class. adding fields just to use for methods can easily bloat a class, especially, if you use one or multiple local variables for a number of methods . . .
I think i had a bit of a misunderstanding about how local vars worked
it makes sense more now
nope. local variables are placed on the stack. this is faster and more efficient than grabbing the (reference type) field from the heap for each access to it . . .
it's smarter to declare the local variable outside of the loop instead of inside though. no need to create it every iteration . . .
this is true, but it depends on the type of variable. a large collection or complex class is better off as a field, but small data and structs — preferred — are mainly used for local variables as the memory comes from the stack, not the heap. local variables are disposed of once the method exits but a field will need to be reset (unless its value is meant to remain the same) . . .
sorry, forgot about this. the second parameter must derive from BaseEventData but you supplied a DragEnterEvent type as the argument. if you don't need to pass any data then use null . . .
something along those lines
How can I set the rotation of the scene view camera manually? Like I would like to set the euler angles directly rather than free rotating?
I managed to select the scene camera but it looks like none of the properties are editable
assuming drag is turned off so that horizontal velocity is constant, projectile motion equations can calculate that. A simple case is straight forward but terrain with uneven height would make that more challenging since you would need to know where the projected arc intersects with a solid object at an arbitrary height.
like in code? or in the UI
Either, I just want to set the euler angles to something specific
its plane not uneven height terrain
Thx
Raycast on the projectile path. Or, you can use equations of constant acceleration motion.
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 5f;
public float jumpForce = 10f;
public float wallJumpForce = 10f;
public float wallStickTime = 0.5f;
public LayerMask wallLayer;
private Rigidbody2D rb;
private bool canJump;
private bool canWallJump;
private bool isSticking;
private float stickTime;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetKey(KeyCode.Space) && canJump)
{
rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
canJump = false;
}
if (Input.GetKey(KeyCode.Space) && canWallJump)
{
rb.AddForce(new Vector2(wallJumpForce, jumpForce), ForceMode2D.Impulse);
canWallJump = false;
}
if (Input.GetKey(KeyCode.Space) && isSticking)
{
stickTime += Time.deltaTime;
if (stickTime >= wallStickTime)
{
isSticking = false;
}
}
else
{
stickTime = 0f;
isSticking = false;
}
}
void FixedUpdate()
{
float moveX = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveX * speed, rb.velocity.y);
if (rb.velocity.x != 0)
{
speed += 0.01f;
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
canJump = true;
}
if (collision.gameObject.CompareTag("Wall"))
{
canWallJump = true;
isSticking = true;
}
}
so i have this code when i try to add it to my empty i get a text box saying...
The script and your class does not share the same name
One is called playercontoler while the other is called PlayerController
Also float moveX = Input.GetAxis("Horizontal"); inside of Fixed Update can have undesirable results.
i didnt see that cuz im dumb and tired
I mean, there is a lot that is wrong with this code. He is going to figure it out.
what should u should i use instead
You don't need to make anything in the FixedUpdate.
You should always check input in Update not fixed update
And just another tid bit of info. Look into how to use enums instead of all your booleans for player state. It will untangle spaghetti boolean logic
StateMachine is a most for a controller
Does anyone know how to refer to the trees of my terrain via script? I currently have a script getting a navmesh agent to take cover at positions working and I want to add the positions of all the trees on my terrain to a kd tree.
i believe what you are looking for is https://docs.unity3d.com/ScriptReference/TreeInstance.html
ah thank you!
var terrain = Terrain.activeTerrain;
var trees = terrain.terrainData.treeInstances;
ok i think the brain rot is getting to me but how should i rewrite this cuz im still abit new to the coding part
The general rule of thumb, is player input is detected in update not Fixed(because of the fixed framerate) And dealing with force/rigidbody is added in Fixed Update mainly for fast moving objects.
just store that in a global variable and apply forces in fixed update
I believe the main reason is using Update instead of Fixed Update for fast moving objects can crap out at very high speeds. I'm not saying that is the case here. But getting in this habit isn't a bad idea.
better?
I'm using resharpner and everything works mostly fine a part from autocompleting unity's inbuilt functions, e.g onCollisionEnter shows but when I try to autocomplete it I just get onCollisionEnter and nothing else while without resharpner it autocomplatets it with whatever is needed. I am also using visual studio
no let me give you a short example of what I mean.
Hi everyone, I'm making progress on my hidden character game and the next pattern I need to create is making all of them bounce off the sides of the camera/screen/game area. I have a game reference as MP4.
And here is a generic reference of a bouncing DVD logo screensaver:
https://www.youtube.com/watch?v=5mGuCdlCcNM&ab_channel=RaúlBlanco
I don't believe there is any difference in behavior between the game reference and the generic reference.
I have a script that can instantiate all the characters onto a grid and give them their own unique direction and speed to transform. I think that to produce this pattern, I need use the cross product to get a vector perpendicular to the original vector of the character and the side of the game area, then replace the character's vector with the perpendicular vector. Then we just need to repeat it every time the character runs into a side of the game area right?
If it hits a corner, what vector should be used? I'm unsure about that.
Bouncing DVD Logo screensaver for modern screens (4K 60fps 16:9) - 10 hours NO LOOP
public class Player : MonoBehaviour
{
private Rigidbody2D _rigidbody2D;
private bool _isGrounded;
private bool _jump;
private float _jumpForce;
private void Update()
{
if (Input.GetButtonDown("Jump") && _isGrounded)
{
_jump = true;
}
}
private void FixedUpdate()
{
ApplyJumpForce();
}
private void ApplyJumpForce()
{
if (!_jump) return;
_jump = false;
_isGrounded = false;
_rigidbody2D.AddForce(new Vector2(0f, _jumpForce), ForceMode2D.Impulse);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
_isGrounded = true;
}
}
}
Take the concept, not the best code. @azure crescent
You could also get the world coordinates of the screen and move some long rectangle objects that form the box of the viewport that have colliders on them. I do this on mobile games all the time.
Depending on how you implement it, hitting a corner is successfully solved by performing the 'bounce' (cross product) of one side, and then using the resultant vector immediately in the calculation of the other side
Hi! I'm trying to goto a position, but i want to be stopped by colliders along the way, like the example image. Is there any way i can do that?
Are you using rigidbodies on your peoples?
Yes.
physics is just math. it's a function of position over time. you know the mass of the object, you know the force of gravity. you know where the ground is
and you know its instantaneous velocity
(I am trying to make a dash mechanic which teleports the charector, but i don't want to clip into a wall)
Yes that is an idea I was considering. This would mean I need to use forces instead of translating. I think I could do that. It's just that most of the other character movement patterns I've made use translate so I'm looking for a way to do this and keeping the movement consistent across patterns.
Okay it seems like cross product would be the way to go. I'll test it.
im getting weird errors when i try this im going to go to sleep cuz my eyes hurt then try to do this when my brain works
you could possibly do a raycast which is limited in length
Why can't I jump in unity
First person 3D
I followed a tutorial because I couldn't get it to work
But it still doesn't work
Idk if its just my computer
Could someone please help
and then hav ethe player go whereever the raycast hit
Code?
Alr
this is what i'd do. fire a raycast forward the length of your tp and go wherever it lands
yeah
k
I'm not to sure how to do it myself but I do know it is possible
Here it is: https://gdl.space/iraqitawex.cs
Couldn't fit on discord so here
good boy
just use the keycode. also IMO you should use rigidbody.addforce with ForceMode.Impulse
ALSO
does that even compile?
have you tried making the radius larger?
Ok I will try
no shot
well the exlamation point on the right hand side of isGrounded isn't doing what you think
Wdym
tell me why its there
"this character is grounded NOT"
I'm struggling with a similar problem - controller my character such that it can respect collisions
You could manually control the objects velocity and then sit it to 0 when ur not moving.
What I'm trying currently is to use a CharacterController component on my player. It lets you perform a Move that will stop when it hits collisions
this works, it looks cursed but it functions the same as it if were on the left
ugh yall drive me crazy
😛
you could also apply a force to the player in the direction of the mouse
can yall just let me be right
the exclamation mark is only a negation when a value follows it. when a value precedes it, it has another function, one i know you didn't intend
i mean obviously you're right
the null forgiving operator came out after brackey's though
stands to reason that it's incorrect
So what should I change to make my player be able to jump?
I just saw that 🙃
did you know typescript and csharp are designed by the same person?
put ! at the left side
as at the end it doesn't really do anything
well the line i showed you has the exclamation mark on the wrong side of the variable. so that's a gimme. why don't you explain how it's misbehaving
have you debugged to see if the jump section of code is being hit? here
It didn't change anything when I moved the exclamation, still no jump
either put a breakpoint and step through to see what's happening or put debug logs to confirm what you think is happening is actually happening
Nothing is happening
It's not being detected
if literally nothing is happening then press play. you should be able to debug your code
what values are you logging?
and where are you logging them
okay
try replacing "Jump" with Keycode.Space
using string literals for input detection is cringe
Did we already confirm that isGrounded is true?
^ could log it
anyone know of a good kdTree script I can yoink?
ty ty
Its in DOTS Plus asset's collection library
Been loving it, can be used in gameobject too
Never regretted getting it!
Is inheriting from Monobehaviour the thing that allows you to create instances of a class?
only a class derived from MonoBehaviour can be attached to a GameObject . . .
So a class that derives from nothing cannot?
If I wanted to write a custom lighting system for a 2d sidescroller, what system would I want to use for that
I already know how I’d calculate the shape of the light, I just don’t know how I would go about getting it into the level as actual light
My original idea was just to use Freeform light2ds and have the script change the light shape but after some quick forums scrolling I have come to the come to the conclusion that that is not possible
What would you guys recommend
Btw this would need to be capable of updating dynamically
How do I go from a list of vertices of a shape in a script to the level being lit in that shape
Just being able to set the shape of Freeform light 2d would work for me so if anybody knows a way for that to be possible dynamically that would work great
that is what that means, yes
but understand that creating an instance of a class and attaching to a gameobject are very different things
one is fundamental to C# and another is just some random Unity functionality
I see, I see
How can I provide a scriptable object with a reference to a class/script?
The class/script is not an instance
So static?
I would assume just the name of the class
I want to do something like this, and I understand this article well, but once I get the light shape, how do I actually get it to render ingame https://ncase.me/sight-and-light/
Create many many many... ray casts
Nononononono I know how to actually do the calculations
Once I have the list of vertices that make up the shape of the light
How to I get it to actually display as a light ingame
Mesh renderer
Kinda like a Freeform light2d, but something able to be updated thru a script
I mean you can use like a shader or something
I wish the Freeform light 2d just let you set the light shape in the script
How can I get a reference to a non-instanced script on an instance of a scriptable object?
Wdym by "non-instanced script"?
I'm not sure how to correctly refer to it...
A script that I dont need to put on any specific game object.
But I want a reference to the script from instances of my scriptable objects
A plain C# class you mean? Not inheriting from MonoBehaviour or ScriptableObject?
I guess that is exactly what I'm getting at, yeah
But I only want it accessed by the scriptable objects i give it to
Well, you can access it the same way as any other class field. Make it public(don't), expose it with a property or a getter method.
How are you "giving it to the scriptable object"?
If you only want it accessible in the class it's declared in, then just make it private🤷♂️
Mmm, I wish my brain was larger so I could accurately explain what I was after...
Let me come at this from another angle
What are the requirements for something to accepted into this slot:
It needs to be a serialized reference by unity(probably wrong wording). Basically, it needs to inherit from MonoBehaviour or ScriptableObject.
I see, hmm
can someone help me with an audio issue? im trying to detect the audio level from the main microphone, but unity doesnt have a built in way of doing this. i found this: https://forum.unity.com/threads/check-current-microphone-input-volume.133501/ but when i try it the output doesnt actually correspond to how loud my voice is. My code:
private static float LevelMax(AudioClip clip, int window)
{
float levelMax = 0;
//get the position to start checking from, which is a window starting from current pos and extending backward by 'window'
var micPosition = Microphone.GetPosition(null)-(window+1);
if (micPosition < 0) return 0;//if we dont have sufficient data yet, return
var waveData = new float[window];//array of floats representing the waveform of the captured window
clip.GetData(waveData, micPosition);//populate wave data with data from the audio clip
// Getting a peak on the last 'window' samples
for (var i = 0; i < window; i++)
{
var wavePeak = waveData[i] * waveData[i];
if (levelMax < wavePeak)
{
levelMax = wavePeak;
}
}
return levelMax;
}```
This is being called in Update(), and it just returns a random float around 0.0025, with no bearing on the volume of my room
It can probably inherit from unity Object, but there's not much point in doing that.
So in my setup, Wooden Sword (Equipment) is a ScriptableObject. (An instance of a scriptable object i think would be correct to say).
I want Ability to be a class that contains a single method.
I want to be able to give different Equipments the same Ability, doing so thru the inspector
Then Ability needs to be an SO as well.
Wonderful, thank you. That makes sense!
Oh, wait. Frick
How would I implement a different method for each Ability?
This is kind of the code setup I'd be looking at. ExampleAbilitySwordSwing is not being accepted into the highlighted slot in the previous picture
Are you trying to drag the script itself?
You'd have to create an asset from the SO and drag that
I see, cool. So for every ability, I'd have only 1 corresponding SO?
Is that a good way to do it?
Ahh, a perfect conversation. I was just about to come in and ask about how people would implement something like the keywords on magic the gathering cards.
It's an okay way. There are people that oppose it radically, but in my opinion it's okay.
what are the alternatives?
Hardcode it.
Mmm... I think SO's are the wrong thing to use for me here.
I'd be creating 100 scripts that inherit from Ability, then adding CreateAssetMenu to them all, but then only ever creating 1 SO per script. mmm
Oh interesting, sounds pretty similar. Information that isnt tied to any specific GO, but can be used by any GO
Really I want to do something a little different, but that is the closest I can get to explaining it with what I know
Lmk if you get a good solution(:
for mtg, there are lots of reused effects and it would be nice to be able to reuse them in the edittor as well rather than hardcoding the same thing onto different cards
Is there a good way of disabling an object's visual rendering, but still display shadows?
Yeah righto I reckon that sounds like what I'm after actually
I want abilities than can be given to weapons that can be equipped by the player, allowing player to use the abilities
any one know how to correctly rotate an object for the rotation handle in unity?
for me it goes way too fast
im not sure how to correctly use the quaternions to fix it
this is my code:
var q = Quaternion.LookRotation(Vector3.forward, Vector3.up);
var forward = Handles.RotationHandle(q, data.Position) * data.Forward;
data.Forward = forward;
not sure why its so damn crazy fast for such a small amount of rotation - how do you fix it?
ah i fixed it
Was it a degrees/radians problem?
no i was using the wrong forward to multiply the rotation
hmm where should i ask about animation rigging?
#🏃┃animation probably
lemme try
maybe its a stupid question, but how do I put a gameobject on top of the cursor? In a position that the camera first sees that gameobject and behind it its the cursor. I am trying it but it seems that the cursor always stays on top.
You mean like picking up an item and then hide the cursor while holding the item?
Either let each door side check with a raycast or stop movement when a collision happens? sth like that
I want to have a gameobject in front the Windows cursor, hiding the cursor. But the cursor needs to still be active and functioning, just behind that gameobject.. And I cant just change the cursors sprite for what I need.
and If I do Cursor.visible = false, the cursor its still in front
the cursor is still in front if you disable it?
I dont want to disable it, just hide it in front of a sprite. I dont know if Im explaining it right, sry for my english. Something like take the Z coordinate of the cursor and put my gameobject in front of that, in a 2d game. But It doesnt seem to work.
If its the hardware cursor, it is ALWAYS on top of everything unless you make it non visible. But if you have a custom sprite attached to your mouseposition, you could offset that in the layer depth. So, what cursor are you using?
Its the hardware cursor, I didnt know that, thank you!
And if your cursor is always visible, even if you set it to false, that is somehow weird. Did you test that in build? Just to be sure its no editor limitation
I've got a question about building from the command line for macOS. In the build window you can select macOS for the target platform, and Intel 64-bit + Apple Silicon for the architecture. What's the equivalent of setting these in the command line? The docs say -buildTarget OSXUniversal and -buildOSXUniversalPlayer respectfully but I don't seem to get anything built, and my logs don't show an obvious error. I unfortunately can't share the logs, but anything to look for / go off would be really useful.
🧐
It was build setting wise, not sure it helps you in command line. I can post again
// It is not visible in any of the managed assemblies, you will never, ever find this
#if UNITY_EDITOR && UNITY_STANDALONE_OSX
// Intel amd64:
UnityEditor.OSXStandalone.UserBuildSettings.architecture = UnityEditor.OSXStandalone.MacOSArchitecture.x64;
// Apple Silicon/M1 ARM64:
UnityEditor.OSXStandalone.UserBuildSettings.architecture = UnityEditor.OSXStandalone.MacOSArchitecture.ARM64;
// macOS Universal or Fat binary:
UnityEditor.OSXStandalone.UserBuildSettings.architecture = UnityEditor.OSXStandalone.MacOSArchitecture.x64ARM64;
#endif
Did you try ARM64 ?
ARM64 isn't an option according to the unity docs under build arguments
https://docs.unity3d.com/2022.2/Documentation/Manual/EditorCommandLineArguments.html
This is the command I use (or rather that teamcity generated, but that i've verified doesn't work running it manually.)
"C:\Program Files\Unity\Hub\Editor\2022.2.2f1\Editor\Unity.exe" -batchmode -projectPath "/my-app-name Project/" -buildTarget OSXUniversal -buildOSX64Player D:\Builds\my-app-name\App\Builds\54_develop_20230126_10391194\MacOS\my-app-name.app -executeMethod Editor.BuildScripts.BuildComponents.TeamCity_PrepBuild_Development -versionFile "C:\BuildAgent\tools/Development MacOS_version.json" -quit -logFile D:\BuildAgent\temp\agentTmp\unityBuildLog-9300905772748481244.txt
The windows equivalent works fine
and the universal thing does not output anything?
Absolutely nothing, and the log doesn't say anything about the build succeeding or failing either
Is it correct to use buildTarget AND buildOSXUniversalPlayer ?
yeah, setting the build target tells unity how to load the project. same as if you go to the build window and click "switch platform" as far as im aware
Did you try with only -buildOSXUniversalPlayer ? Just guessing here while googling 😄
Oh wait, you are trying to build for mac on a windows machine?
How to properly destroy a DDOL GameObejct from another script? I thought Destroy(Class.gameObject) would do it but it gives me a NullReferenceException
you need to get the instance of that class, not the class itself
I already have an instance variable in my DDOL class, can I make it public and use that? Is that safe?
it needs to be static to be a correct instance
Otherwise its not a singleton as what you would DDOL use for
It's private static at the moment
public static and then Class.instance.gameObject can be destroy
Great thanks
I am not sure you can easily build for mac from windows. did you try through the build settings?
yep, and I know it works
Weird, but maybe you cant build for M1, only OSX universal
Nope
You can build for everything, I've done it, verified it works
Even have it running on our dev mac
yeah, a m1 mac is good at emulating standard intel mac builds
Command line will just not write a binary
No, i've verified it's not running under rosetta
Okay, then this is either lacking Unity who are behind of command line tools or we are missing some weird thing here 😄
Hi all,
I'm hoping someone can point me in the right direction on this as it's driving me nuts. lol.
I have a particle system which gets instantiated when a ball hits the walls of a tunnel (to 'simulate' a type of shield hit).
The problem I'm having is getting the particle system to 'align' with the geometry of the tunnel.
I have the system set to 'Local' space, but it keeps dinging up with random 'directions'.
Anyone have any ideas? 😕
`private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "ShieldWall")
{
Debug.Log("Ball Impacted");
Vector3 impactPoint = collision.contacts[0].point;
Quaternion impactRotation = Quaternion.FromToRotation(Vector3.up, collision.contacts[0].normal);
GameObject shieldHit = Instantiate(shieldParticle, impactPoint, impactRotation);
Destroy(shieldHit, 1);
}
}`
Actually thinking about it yesterday I did an apple silicon only build and it built and ran fine
I'm leaning on the side of command line seriously lacking, but it should still output a binary.
The alternative is I just have build scripts for each build I want, load Unity in batch mode and run the build script. Kind of defeats what I'm going for but at least it might work
Try pausing when the particle system is instantiated and check it's inspector. Does it correspond to what you expect? Is it positioned and rotated the way you make it in code? Printing the relevant values before/after the instantiation might also be useful.
This is what's happening when my car hits (using the car to test)
I would check whether collision contact array returns the correct normal, and then try some other way of calculating the impact quaternion - Quaternion.LookRotation or even Quaternion.Euler
Well, I just tried with a plane with material on it, and it works fine, so I'm just gonna go with that approach. lol.
Also if the ShieldWall object was modelled in blender, it's worth it to check it for backfacing polygons that happen to have their normal turned around, hiding the backfaces
(if it has a nonconvex mesh collider)
Is using Reflection a bad way to save and load data?
Does anyone know how I can capture the bounds (frustrum) of a 3d camera, so that I can set the ortographic size of another 2D camera to always be just large enough as what the player sees?
I've got this code from ChatGPT:
float perspectiveFov = main3DCamera.fieldOfView;
float aspectRatio = main3DCamera.aspect;
// Calculate the vertical size of the frustum at the camera's distance from the plane
float frustumHeight = 2.0f * Mathf.Tan(perspectiveFov * 0.5f * Mathf.Deg2Rad) * main3DCamera.transform.position.y;
// Divide by the aspect ratio to get the horizontal size of the frustum
float frustumWidth = frustumHeight * aspectRatio;
// Set the orthographic size of the lighting camera to half of the frustum width
lightingCamera.orthographicSize = -frustumWidth * 0.5f;
However, it only takes into consideration the zoom of the perspective camera. It also changes perspective (angle) by changing transform.rotation.x, so it can see more of the plane ahead of it, effectively going from top-down to 2.5D
Here's an example:
You can see that at a certain angle of camera rotation the lighting camera's orthographic size is too small so there is no lighting (shadows get lost)
You could use reflection for saving data. If your save is small and not being made each frame, reflection wouldnt be an issue. In fact, most serialising library use reflection.
BUT, if you want clean code, you need to separate your saved data, from your game data.
BUT, if you are saving large word, reflection could add a decent amount of time.
You could use partial class to generate save procedure in each class and use BinaryStream.
You could use System.Reflection.Emit, which is faster but would be harder to implement.
You could, and should, use 1st/3rd party library for saving data. (JsonUtility)
I have EzSave but I just didn't feel like implementing it because my game is also Networked. I want the capability of saving locally and also sending to the cloud
Which only implies manipulating the resulting files and has no impact on the save data itself.
Have a Quaternion question. Let's say I want to rotate a gameobject like a spaceship that may have it's Y axis not pointing up. If it's rolled onto its side and I'm in it and want to turn to the right... how could I manipulate a Quat to do this? I tried just doing transform.TransformDirection(0, 1, 0) (for yaw) and then doing Euler off of that and multiplying the existing rotation by the new rotation, but it is not working as intended
goal is a 6 degrees of freedom control, kind of like in the game Descent, X4, really any space game that lets you roll your ship
basically i want Euler() to take into account the existing rotation
nvm, I think it was working all along. sigh
transform.rotation *= incrementalRotation;```
turnVec is from mouse input
Can't you ask ChatGPT again?
Makes me wonder if you understand what the code does at all
Your issue might be beyond your code you are showing. Is the light camera being rotate as well ?
#💻┃code-beginner pinned in the top right has starter courses/tutorials.
Is it possible to get params for lets say transform as an enum, so rotation, position, scale? Or should I just do my own switchcase with a custom enum. I want an animation scriptable object, that can actually select, what I want to modify on the gameobject I put it on
I guess easiest way is to just get my own enum here
Why would you need it as an enum?
Can't you use if(transform.position.x == i) and such?
Lets imagine a function, where you can pass in the transform.position or rotation as a "value". Based on that and an animationcurve you create, you can then animate that value
Hey, I'm struggling to find to make a container fit my text (tmp). I found text.bounds which seems to work, although sometimes the results isn't perfect, larger than needed. Is there any other easy to set up way to do it?
Show a photo?
So you are trying to make the bubble fit the text?
Yeah basically
hey can i ask questions regarding photon here?
I'd say ask in #archived-networking
ok thansk
#📲┃ui-ux Id say
No need for coding here
The solution would be code but sure whatever
You do not need code to fit your container to the text. all done with UI components
And that would fit it dinamically?
I'm setting the string of the text through script
I think you would have to child the bubble to the text and set it to expand. I believe
Why cant I use ScriptableObject.CreateInstance with a custom type SO ? It just says that it cant be converted from CustomSO to unityengine.SO
🤔
oh its because my class doesnt derive from SO

Good chat
Debug.Log(Physics.Raycast(landingRay));```
why might this return false when the object is above a cube with a collider?
It probably is a stupid thing that I keep missing
Hey,
How can I get the current renderer in an LOD Group?
// truncated
public GameObject tree;
// truncated
MeshRenderer meshRenderer = null;
LODGroup lodGroup = tree.GetComponent<LODGroup>();
is it possible to access a gameobject inside the prefab from the scriptable object?
transform.position could be more than one unit away from the box
Everything's possible, as long as you understand how references work and how to pass them around
When I reference a GameObject on ScriptableObject, it only accepts a prefab format due to being scene independent
maybe I can just do GameObject.Find() or something
I thought Vector.down was only direction and had nothing to do with the length though in either case that doesn't seem to be the reason
It's a vector pointing down with length 1
I know what it is. But you need 2 points to draw a line don't you?
yes
By default Unity capsules have a height of 2
And pivot in the center
Meaning a ray with length 1 won't clear the size of the capsule
I extended it to 100 units before answering
Make your ray longer or start it from a point lower down
How? Show that code
Ray landingRay = new Ray(transform.position, Vector3.down * 100);
Ok good
This still doesn't work?
Show the scene setup and the inspector of the box/cube if not
A ray is an infinite line starting at origin and going in some direction.
Just a stupid dumb question, wouldn't the ray hit player itself if there's no layermask query 
In Unity this isn't true in all cases
For Raycast there's a separate parameter for length of the ray
It does default to infinity though
I am quoting Unity doc
https://docs.unity3d.com/ScriptReference/Ray.html
In 3d it doesn't hit a collider it starts inside
And yet, it's not true in all circumstances
In this one it is.
Ooo ok
For Debug.DrawRay the length of the ray matters for example
yeah, I learned that while trying to find out the problem
scene is just this
well, the box is just a box honestly as a place holder for ground there is nothing specific about it
was I supposed to just send links of the pics?
as for layers, everything should collide with everything
player is an empty object at (0, 0, 0) position and the capsule collider is a component of the cylinder which is a child of the player
if player is at 0,0,0 where is the box?
is the raycast starting inside the box?
the box is at -.5 with the y scale =1
put it lower
hmm, let me check that one
that may have the raycast starting slightly inside the box
Hi,
Why does it seem like that static batching is not working?
maybe share some details? DOesn't seem code related thouh
Doing this doesn't work. I'm running it for 192 objects.
gameObject.isStatic = true;
I don't think you can make them static at runtime and get static batching to work
you have to do it in the scene at edit time
it's the kind of thing that's baked in the editor
you can probably have 2 of the same object, one static one dynamic and use them interchangeably instead
I never used static batching so don't really know if there would be any point
I'm optimizing terrain by putting every tree in a giant mesh and setting it to static, but it doesn't seem to work.
I'm still getting the same amount of draw calls.
I have the issue of this not working, not working as in I cannot type anything in the text field, this is an editor script and yes its in the editor folder, every other text field is working fine,
Is it just that you cannot store string temporarily in this function (which is OnGUI) and all the other text fields link to some otehr SO? If so how do I solve this
This is what it looks like right now, cannot type in this field
And then it also fails when I actually go and try to create the asset with the code you can see there, I thought maybe its because I am not giving it a name so I added that functionality, but idk why at this point
you're declaring that as an empty string right there
string newObjectName = "";
every time it renders the GUI it will make it empty
I thoguht im just decalring it in order to say well this is a variable, be prepared for it to come up
that's an actual string
and you pass it in to populate the text field
store that string somewhere more permanent
in the Editor object itself or whatever serialized asset you're editing here
out side of OnGUI?
yes
you'll want to initialize it yes
and then it gets populated with whatever I put into the text field?
wont it stay in the editor script forever then though? >_>
Only for the life of that variable, which is the life of whatever object this is
some editor
until i like manually delete it that is
because ideally i want it to be empty as soon as I hit the + button
try it
okay
then do newObjectName = ""; in the code for the button
Well I am still getting the error cant create object
you never mentioned that error
what error is that
UnityException: Creating asset at path failed.
DialogueEditor.OnGUI () (at Assets/Scripts/Editor/DialogueEditor.cs:61)
so what's that path
print it out
Uhm yea one sec
probably that folder doesn't exist
its trying to find a folder that would really be an asset
OHHHH I KNOW WHY
the way i get the path is
"Just take the path of the currenlty selected Object, and then just add the name.asset"
so thats why its wanky
But how can I get JUST the path and not the Test.Asset
Test is the currently active dialogue object
im edting that object in the editor basically
I cant very well be like "Get the path and then remove the last bit"
well you could but that's kinda hackyish
Can I somehow say "place it in the same folder as this file"
GetDirectoryName('C:\MyDir\MySubDir\myfile.ext') returns 'C:\MyDir\MySubDir'
seems promising
I'll try that thank you
Is there a way to auto manage delegates based on an interface without constant scanning of objects and without explicit registration copy and pasted everywhere?
What I want is that when CustomHandler is created, it finds all objects that implement HandleMe and registers them (this can be a complete scan). Then all new Objects that implement HandleMe should then register themselves (this is the part I can't figure out without duplicating code).
class SomeObject : HandleMe {
public void doWhenHandle() { }
}
class CustomeHandler {
public delegate Handle;
public void Awake() {
\\ Find all existing objects that should be added
}
public void Update() {
if (something) handle();
}
}
For the registration of objects created after the fact, I could do something in their Awake method but I want to avoid having to code that every time. I thought about using default methods in the HandleMe interface but that would then hide the methods if the object wants to actually do something in Awake.
Who or what is creating the objects?
If it's being done from one place maybe you do the registration there?
or make the thing that creates them fire a static event
and CustomHandler listens for that event
Ohhh myy gooddd PraetorBlue youre the best, youre the MVP of this server, no matter who needs help you like always find the solution, thank you!
So the fun part is that I'm using Photon Fusion so it may be instantiated by Fusions Spawn functionality. There's Spawned() and AfterSpawned() methods that are similar to Awake, but I'm not sure if I have access to automatically do something on every Spawn.
So its possible to serialize a class and create new instances of that class from the inspector. In the example below you would be able to populate the items array in the Shop class from the inspector.
[Serializable]
public class Item {
public string name;
public string price;
}
public class Shop : Monobehaviour {
public Item[] items;
}
But what if I wanted to to the same with various types? Is there a way I could make a dropdown that shows the type and then shows the correct fields once selected?
[Serializable]
public class Potion : Item {
public Color color;
}
yes but it would require two things:
- the use of
[SerializeReference] - a little custom editor code to create the UI to create the objects as desired
See #↕️┃editor-extensions
Yes, I logged it and its true
Doesn't work
Anyone know what to do?
ok cool, thanks. I saw the SerializeReference page, but I didnt understand it. Got me thinking either way
I am adding elements of one list to a new list, and I want to make sure that as I add them that they do not already exist in my new list.
Maybe the new list should be a HashSet?
Do you need the order to be preserved?
order is not important
Can't we just use
if(!list.contains(object)) list.add(object);
Here?
I will try that
sure but that's really fucking slow
No I'm asking praetor lmao
HashSet is the right way to do it
Ahh alright
The list will only ever be a handful of objects
doesn't matter much then, but HashSet is still semantically cleaner
Why can't I jump in unity
you just do:
myHashSet.UnionWith(myList);``` and you're done
Because you didn't make a script to do so
I did
I also followed tutorial cuz my script didn't work
And the tutorial didn't work
Could It be a problem with my system itself
HashSet contains no duplicates, therefore, eliminating the need to check for an element before adding . . .
no
how else would anyone be able to check and see what the problem is? also, this sounds like a #💻┃code-beginner issue . . .
Ah ok, will look it up for study later tonight, thanks!
never the issue. make sure your code matches the tutorial code and your objects are setup correctly inside the editor . . .
Yea i checked multiple times
Its the same code
Here's the code
I tried logging it
But i dont even think its detecting my space key
Can always check that with a quick debug
I have checked
Nothing shows up in debug
Then it's probably isGrounded issue
It's not
I logged that
And it showed up in the debug
Everytime I hit the ground
Ok so let's do 2 things
Check for "isGrounded" and Check for "jump" seperately, and see if you get debugs for both of them
Also can just make isGrounded bool serialized so we don't have to debug that, and can just look at it in inspector
IsGrounded works
Jump doesn't
In debug
Maybe "jump" doesn't exist in the valid inputs, did you try using KeyCode.Space?
It's frankly better than string comparison anyway
It says it does not exist in current context
How does hashset work? Thanks for the suggestion - it appears to be working. I just don't know how.
Spelling mistake maybe, is your IDE configured?

I'm gonna try
move to #💻┃code-beginner and check the #854851968446365696 on how to configure your IDE . . .
Ok sorry
Would it be possible for me to make something like freeform 2d light but have the shape be able to be edited by a script?
Hello there, I have a problem where my boss (acting like a turret) isn't aiming down to the player properly, it points at the player direction, but with the wrong rotation
looks like this
Some people in a forums discussion I was looking at say that you cant edit that
Ah cool!!!!
But can I update this while the game is running for dynamic lights?
Or does it need to happen only at the beginning
I don't see why not
Cool
Do you prefer to merge git feature branches with -no-ff?
what about main/develop to master or hotfix to master?
can someone help me, I´m not figuring out how to fix the boss head rotation towards the player
Atan2
where would I put that in my code?
Is it good practice to put conditions on the calling of a function rather than inside? I'm thinking ground check for a jump function and such. It would improve performance right?
Any performance improvement would be negligible, however, having the conditions inside the called method ensures that you have a consistent usage
It also makes it easier to understand and fix errors so I'll them inside. Thanks 💯
Is this 2d or 3d
3D
.
code
I'm hardstuck on this. I'll gift nitro to whoever can figure out whats wrong.
https://stackoverflow.com/questions/75242716/unity-engine-using-kd-tree-to-search-for-nearest-transform-is-not-returning-any?noredirect=1#comment132775149_75242716
NEVERMIND I GOT IT WORKING OH MY GOD
I got it almost working, but the head is facing sideways
even if I rotate it, the head still faces that way
Are there multipl objects with "player" tag in the scene?
nop
In that case i would recommend caching your player with serializeField first, and for testing pull the "lookat" line outside the if condition to see if it's working correctly
Is it possible to check the inspector of a different scene during runtime? My checkpoints objects seem to be surviving the Destroy() function that's called on SceneLoad
That will happen if:
- You marked them with DontDestroyOnLoad
OR - You laoded your new scene additively
not sure what you mean about "checking the inspector of a different scene"
Can an editor window make an event call (tahts just what im calling an event happening) and a scriptable object listen to said event?
Because I need a way to update a node that is a scriptable object but I cant use OnGUI because that is editor based
and I have an editor that COULD theoretically call an event but im unsure if that interaction even works
All I need is for the Scriptable object to always access a certain Editor Window and check what is the currently active object in it, but idk what I should use for that, the Editor WIndows active Object obviously only gets updated once in a while so IDK what exactly to use to update that "active object" in the scriptable object
Class Goal handles the Scene loading and it's a regular LoadScene() to get back to the main menu
Class CheckPointManager has a singleton to keep the CheckPoints through Scene reloads
Class CheckPoint sets the transform.position
My problem is that from the main menu when I go back into the level, it loads at the last checkpoint. I assume it's because my PlayerManager's Awake() function loads the last transform.position from the CheckPoint class as it somehow survives? I'm not sure to check if the singleton is properly destroyed
Class CheckPointManager has a singleton to keep the CheckPoints through Scene reloads
^um
is this a DDOL singleton?
Naturally it lives through scenes
Greetings, how do I create a 'DestroyAfterTime' script to be triggered after another specific script?
Destroy() already has an overload that takes a float time
which will delay the Destruction for that time
not sure if that's what you're asking for
after another specific script
is kinda vague so not sure what you mean by it
what is JointDismemberPhysics?
It's a script for dismembering ragdoll joints after a strong collision
a script, or a method?
which one lol
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
apologies
long story short, I'm trying to combine the two scripts at the end of the day
which scripts
Destroy(CheckPointManager.instance.gameObject); will not Destroy it?
JointDismemberPhysics and DestroyAfterTime
sure it will, but you'll want to set CheckPointManager.instance to null too, otherwise you're keeping that orhpan object around (with all its data)
Are you planning to show the code?
yes
Ok ok dope thanks
under the visual scripting channel?
Are you using usual Visual Scripting? (Bolt)
Visual Studio actually
ok Ill try again
// using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Joint))]
public class JointDismemberPhysics : MonoBehaviour {
[Header("Parameters")]
[ReadOnlyField(true)]public float breakForce = 1000;
[ReadOnlyField(true)]public float breakTorque = 1000;
private RagdollDismembermentVisual visual;
private Joint joint;
private float sqrBreakForce;
private float sqrBreakTorque;
private void Awake()
{
sqrBreakForce = breakForce * breakForce;
sqrBreakTorque = breakTorque * breakTorque;
visual = GetComponentInParent<RagdollDismembermentVisual>();
joint = GetComponent<Joint>();
visual.OnDismemberCompleted.AddListener((string name) =>
{
if (name == this.name)
{
joint.breakForce = 0;
Destroy(this);
}
});
}
private void FixedUpdate()
{
var sqrTimeScale = Time.timeScale * Time.timeScale;
if (joint.currentForce.sqrMagnitude* sqrTimeScale > sqrBreakForce ||
joint.currentTorque.sqrMagnitude * sqrTimeScale > sqrBreakTorque)
{
BreakJoint();
}
}
public void BreakJoint()
{
visual.Dismember(name);
enabled = false;
}
}
Nope, still not right
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
If you don't understand what this says, say so
You're not making much sense right now
how do i clamp the magnitude of a vector without normalizing it?
i'm making a player movement script and i'm just doing this
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;```
but because of that, you go faster if you hold, say, W and D at the same time, and i don't want that, but just using move.normalized wouldn't work
Hello guys, I have this function but it's not working as intended
void Zoom()
{
Vector2 distanceFromCursor = (cam.ScreenToWorldPoint(Input.mousePosition) - cam.transform.position);
if (Input.mouseScrollDelta.y < 0f)
{
cineMachine.m_Lens.OrthographicSize += 0.1f * sensitivity;
}
else if (Input.mouseScrollDelta.y > 0f)
{
cineMachine.transform.Translate(distanceFromCursor * Time.deltaTime);
cineMachine.m_Lens.OrthographicSize -= 0.1f * sensitivity;
}
cineMachine.m_Lens.OrthographicSize = Mathf.Clamp(cineMachine.m_Lens.OrthographicSize, 1f, 100f);
GameManager.orthoSize = cineMachine.m_Lens.OrthographicSize;
}
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Yes yes, I misclicked
Anyways, so what I want is a zoom that tracks the position of the mouse
So it doesn't zoom to the center of the screen all the time, but it feels off, I will send a video (also I'm using cinemachine)
set your cam to temp look at set target where mouse is
void FollowPlanet()
{
if(Input.GetMouseButtonDown(1))
{
Vector2 mousePos = Input.mousePosition;
Ray mouseRay = cam.ScreenPointToRay(mousePos);
RaycastHit2D hitInfo = Physics2D.Raycast(mouseRay.origin, mouseRay.direction);
if(hitInfo.collider != null)
{
cineMachine.m_Follow = hitInfo.collider.transform;
}
else
{
cineMachine.m_Follow = null;
}
}
}
Like here?
similarly, yea does it not work when u zoom onto this target?
set the follow target to be a temp zoom target you create
or create an empty transform since I think follow target only uses transform ?
then make that follow mouse pointer whenever you're zooming
hmm alrighty imma try that
wait can I just create a new gameobject reference and instantiate that?
I forgot how to create an empty transform...
any way to do/fix this?
but to fix your issue you just normalize the vector then multiply by speed
can someone explain to me why the upper version is wrong even though I thoguht thats how we have to do it? just trying to learn here c:
and whats the error tell you
well it says that its trying to convert a void into string or the other way around but I just dont see it
EditorGUILayout.LabelField doesn't return anything so it cannot be assigned to something else
What kind of void I havent even written a void here
ohhhh
I thoguht the top line was saying
LabelField returns, a void
"take the i value of this item, then for that number do this thing"
like for example I thought it would take the first object and in the first line display the field, then so on for the rest
but alas I have been wrong
thanks for teaching me guys
Hello! I'm working on a 2D "decal" system for a pixel art game. Code below works almost perfectly, but every decal is moved by a half pixel. Do you know how to fix that? (The green stuff on the pixture are the decals and grid behind them is a testing object)
private void SnapToPixelGrid()
{
transform.localPosition = new Vector3(
RoundToNearestGrid(transform.localPosition.x),
RoundToNearestGrid(transform.localPosition.y),
transform.localPosition.y);
}
float RoundToNearestGrid(float pos)
{
float xDiff = pos % pixelGridSize;
pos -= xDiff;
if (xDiff > (pixelGridSize / 2))
{
pos += pixelGridSize;
}
return pos;
}
oh beautiful, clampmagnitude is exactly what i needed
(the second way didn't work, i tried it)
clamp magnitude is not the solution you are looking for. it is the answer to your first question. the solution you need (and has been proven to work thousands of times now) is to normalize your input before scaling it by your desired speed
but the Horizontal and Vertical axises smoothly go from 0 to 1 and back the when you're pressing the buttons, so normalizing the move vector would mean that you would still be moving when you release the move buttons because the axis value would still need to go from 1 to 0 unless you mean normalizing the vector even before multiplying it by Horizontal and Vertical axis which i have just realized you might've meant
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = (transform.right + transform.forward).normalized;
move.x *= x;
move.z *= z;
i suppose doing this is better?
why would i need to normalize my input
btw you can use transform.TransformDirection to convert the direction to be relative to the rotation of the object instead of multiplying the transform.right and transform.forward
to prevent literally the exact issue you are facing. if you don't normalize a Vector containing your input then you will move faster diagonally than on any single axis
no i need to normalize the vector with transform.right and transform.forward
if i don't normalize it, it will have the magnitude of sqrt(2)
again, don't even bother using those, use the TransformDirection method instead
but if you don't normalize your input then it will also be (1,0,1) when moving diagonally
But then it will also ignore the acceleration of input axes which may not be wanted. ClampMagnitude is the solution I think solves that
exactly that
Just clamp the magnitude of the input vector to 1
the input vector?
Vector3(Horizontal, 0, Vertical)
but you just said it'll ignore the acceleration of input axes
It doesnt if you ClampMagnitude. Normalizing does
Oh I see ye
But I think normalizing the (transform.right, 0, transform.forward) vector is better though
or using TransformDirection like boxfriend said
Id clamp the input then multiply it by speed and deltaTime and in the end convert from local to world space using TransformDirection
Does anyone actually know hood tuturials for vr coding
would you really need to clamp the input if you're using TransformDirection?
I don't think they do a lot of VR coding in the hood
yes, you will still need to clamp/normalize your input
ok fair
That didn't work as well for me, I tried it
I still think the translate method could work
wait just realized you're using m_follow
I think it should be the lookat target
hmm ok
Hello, rider can't find the Resources class from UnityEngine, even with a using UnityEngine; in my files
I explicitly need to type UnityEngine.Resources to make it work, but what's disturbing is that happened suddenly, before, everything was fine...
Any idea ?
The error: The type or namespace name 'Load' does not exist in the namespace 'Resources' (are you missing an assembly reference?)
probably a missconfigured IDE / corrupt solution files
See it interprets Resources as a namespace instead of a class, something's wrong here
The compiler picked up the wrong one, do you have your own Resources namespace?
You'll need to fully qualify the name UnityEngine.Resources.Load<T>("...") if you wish to keep your own Resources namespace
tested it, I think I used wrong looked at :p plus Im in 3D.so maybe moving it might be better than lookat
No that's ok. What happened I think is, because my script files are stored in a Resources folder, rider created the Resources namespace for me when I created a file
I usually create files from explorer or unity, that's why it didn't happen before..
Ah yeah that's why, Unity applies their own script template which dumps everything into the global namespace
Yup
why store your scripts in resources?
Are you panning with something else?
I may not need them to be in Resources, but since i put every asset in Resources, I said maybe why not storing scripts here too
I guess that's wrong
im only moving target transform in inspector and changing ortho size
yeah try not to
Okay, gonna clean up all this once
Hmm I think I'm gonna use an alternate method
Otherwise, you guys know how I can remove this error from spamming my Console ?
[Collab] Collab service is deprecated and has been replaced with PlasticSCM
I uninstalled the Version Control package, but it keeps spamming this error every second
that's not blocking me from building the project or whatever, but it's annoying
Ok so my previous method works but I just had to scale up the vector to keep up with the zoom
However, this skips a lot cause of the mouseDelta
Is there a workaround for this?
{
Vector2 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
cineMachine.transform.Translate(distanceFromCursor * Time.deltaTime * zoomSpeed);
cineMachine.m_Lens.OrthographicSize -= 0.1f * sensitivity;
}
The piece of code btw
zoomSpeed is the variable I can change and the larger it is, the faster it zooms in butt it skips a lot
Acc nvm it's not that big of an issue
hello, i want to make a map in the style of avorion, ie : a big square map divided in a lot of square, i want to be able to visualise the whole map at once, being 50x50 or even 100x100 or maybe more. each tile would have to contain data about what is in this tile and be able to show it when i click with my mouse on it.
The main issue i have is that i don't really know how would i approach that, there's the tile system but i'm not sure it fits that purpose really well.
The other option i had was making every tile be a gameobject and have a script to generate the map randomly assigning stuff to each tile. that option would lead to having a lot of displayed gameobject which isn't optimal.
Another way i'm thinking about would be to have few gameobjects but the data is accessed by looking at where the mouse is on that gameobject which could allow to have only 1 gameobject for a square map and i would just have to find a way to put highlights on the tile i am looking at.
My question being, i feel very confused and don't know which of these options is suitable or would work, which do you think is better or is there another way i didn't see?
Also here's kinda what it will look like on a very bad sketch
I'm completely lost trying to manually destroy a DDOL class from another class when a new scene loads.
Currently I have Class cpm
Destroy(cpm.gameObject)
However it just does not work
cpm inherits from MonoBehaviour and is a component attached to a GameObject with DDOL, and calling Destroy on that GameObject doesn't destroy it? are you sure it's not just being created again in the new scene?
I have a PlayerManager that sets the player position to whatever lastCheckPointPos is. By default lastCheckPointPos is a set Vector2 at the beginning of the level.
However after the scene changes to the main menu and I go back into the first level, I spawn at the last checkpoint. My CheckPointManager is the class with DDOL
I'd try to hold on to the idea of separating the logic of your game from the representation of it - your data for each tile and what each tile does can be entirely written with simple C# classes. You could then start with the idea of having a GameObject for each tile just as a point of interaction to access the tile data class underneath such as handling OnClick events, etc, and if performance becomes a concern the data layer will be intact and you can just change how it's represented
you might need to share your code for PlayerManager & CheckPointManager
My CheckPoint script is where I set the transform.position
your PlayerManager isn't interacting with CheckPointManager here?
No
so why would destroying CheckPointManager do anything?
My checkpoints object are children of my CheckPointManager
the lastCheckPointPos is what you need to look at resetting when the scene starts/returns to main menu
this doesn't look like it has anything to do with the object you're trying to destroy
A normal c# class would be able to store the data or would i need to use scriptable objects or something else to retain the data from each tile? ( Haven't coded in a while i have to admit )
How do I have this accelerate over time?
Right now it's constant and it doesn't feel as good
yes, though you wont be able to set values in the inspector - you'll need to think about how you're saving/loading the data of your game, lots of ways to do that via Json, CSV, SO's, etc
Do you have a basic understanding of mathematics?
Oh god what did I do
...yes
Are you updating currentOrthoSize though?
increase the value of orbitZoomSpeed * Time.deltaTime over time then it will accellerate
Yes
{
while(true)
{
float currentOrthoSize = cineMachine.m_Lens.OrthographicSize;
cineMachine.m_Lens.OrthographicSize = Mathf.MoveTowards(currentOrthoSize, expectedOrtho, orbitZoomSpeed * Time.deltaTime);
if(cineMachine.m_Lens.OrthographicSize == expectedOrtho)
{
break;
}
yield return null;
}
}
Ok yeah I think I can do it
Why are you getting the currentOrthoSize every time?
Looks like it should work, unless the == fails because of floating point imprecision
Oh yeah mb
Yeah I thought about that too but it's fine
Could use Mathf.Approximately to be sure
Nevermind, this is necessary
no, this is bad in this context
set it once not every time in the loop, you are almost implementing a lerp
But I can't cause I need it to lerp
keyword almost
cineMachine.m_Lens.OrthographicSize = Mathf.MoveTowards(currentOrthoSize, expectedOrtho, orbitZoomSpeed * Time.deltaTime);
orbitZoomSpeed += 1f;
orbitZoomSpeed = Mathf.Clamp(orbitZoomSpeed, orbitZoomSpeed, maxOrbitZoomSpeed);
Unfortunately this did not work either
yes because this orbitZoomSpeed * Time.deltaTime is wrong, as I pointed out 10 minutes ago
You mean here?
Wdym by wrong
soo, what should it be then?
I did ask if you understood basic maths
I do, however I do not understand it as well when it comes to C# and Unity, I'm barely surviving here
you need a value that goes from 0 towards 1 incrementing every loop, to accelerate you need an additional multiplier to make that acceleration
Don't blame me, blame this guy, he also used speed
well dont follow what idiots do then
basic maths
float maxDelta = 0f;
while (true)
{
cineMachine.m_Lens.OrthographicSize = Mathf.MoveTowards(currentOrthoSize, expectedOrtho, maxDelta);
maxDelta += 0.1f;
maxDelta = Mathf.Clamp01(maxDelta);
if (cineMachine.m_Lens.OrthographicSize == expectedOrtho)
{
break;
}
yield return null;
}
}
Idk man but this don't work
i give up
Lemme just tell you, you are not a very patient person
Tbf I'm starting to second guess myself
Mathf.MoveTowards(current, target, maxdelta);
I might have been thinking of lerp where you'd want a constant starting point and endpoint
I have been drinking though..
Now I'm extra confused
I'll read this tho
Are you sure you're calling this correctly? And orbitZoomSpeed is an high enough value (since you multiply it by about 0.01)
For testing purposes you could try throwing in a really high value orbitZoomSpeed, and that should get clamped to the expectedOrtho
You don't need the currentOrthoSize variable at all, you can just plug the OrthographicSize there
cineMachine.m_Lens.OrthographicSize = Mathf.MoveTowards(cineMachine.m_Lens.OrthographicSize, expectedOrtho, someSpeed * Time.deltaTime);
Edit - changed maxDelta to a value multiplied by deltaTime
Idk what the others are saying. This is not Lerp, it is MoveTowards
I just threw a link, suggested they use lerp instead
Yeah but Steve was talking about 0..1 range which is a lerp thing
Didnt this version work just fine?
yes Idk if I'd call Taro an idiot xD
public class test : MonoBehaviour
{
void Start() => StartCoroutine(SmoothOrbit(200, 10));
IEnumerator SmoothOrbit(float expectedOrtho, float orbitZoomSpeed)
{
while (true)
{
Camera.main.orthographicSize = Mathf.MoveTowards(Camera.main.orthographicSize, expectedOrtho, orbitZoomSpeed * Time.deltaTime);
if (Camera.main.orthographicSize >= expectedOrtho)
break;
yield return null;
}
}
}
Just threw this together and it just works 🤷♂️
The >= is a bit sus to me
What if it starts at a larger value already
oh sure true
it was just for demonstration purposes, to show that there is nothing wrong with the logic
So seems like Steve is the only one confused here lol
like, you can throw that script anywhere in your scene, and you should just see an orthographic camera's size increase
That's what confused me too...
This version worked fine
Yeah I tried that and replaced it with == (or mathf.approx
In conclusion, don't insult my boy Taro
I'm making a game with an infinite procedural world with randomly generated structures, objects, etc. The idea is that I add pathfinding so that NPCs and animals can move around and go inside of houses and such. The problem however is that the current method I'm using is too slow and unreliable. My current approach is to separate the world into chunks of 8x8 blocks that I'm using the A* algorithm on to generate a general path. Then I use A* again but this time I run it on the blocks that are inside of these chunks to generate a path.
My question is, what would be a better approach to this, or how would I be able to optimize (maybe using threading or something? No clue)...
Have you seen this?
https://github.com/h8man/NavMeshPlus
Main Code
https://pastebin.com/YLDBCPuM
https://pastebin.com/Fm5kp8Lk
(Inherits from these)
https://pastebin.com/dZQukmaF
https://pastebin.com/H9TSpQv2
https://pastebin.com/Zw79eyuH
Can someone help me? I am absolutely losing my mind ive been at this for like hours.
All I want to do is get the Editor window automatically display parent
Dialogue Objects connected to its node on the left and child/answer Dialogue Objects to automatically display on the right with the connections
Everything that is required is theoretically there I just cant figure out this last bit where I have to feed the start and end pos into DrawNodeCurve T_T
Please feel free to DM me as this might not get solved immediately
I tried literally everything in the DialogueNode script thats why there are so many DEW things at the top
and its kind of a mess right now because I tried so many things ;(
This should theoretically get the start and end position and then draw the like connection between the nodes (each dialogue object being a node)
If someone finds this later and wants to help me just msg me DM
cant figure out how to make this work
as the wiki doesnt show how to use it besides setting it up
is it just a normal navmesh?
No this is a 3rd party one, unity navmesh is only available in 3d
Did you look at that page?
yes i did
I haven't used it myself yet, but I am planning to
If someone finds this later and wants to
Hello guys, hope all is well. Can someone please help me connect my login scene to my register scene
Hey uh - whats one of those sites where you can put ur code in for others to see
pastebin?
thats the one
Ive struggled with that in the past myself, Ive never figured it out aha
Alrighty - Hey so I made this kinda.. flying lump thing
I just wanted to to flying with acceleration and deceleration
pls somone help im trying to make car like beamng drive becasue i cant afford it
i made a car it has wheels window but they all fell apart
how connect all parts together
and Im aware this is probably done really stupidly
are they under the same parent?
it does not function
lmao
i put them under an empty object
hm
is that ok
List<Vector4> openNodes=new List<Vector4>{new Vector4(startCell.x,startCell.y,0,-1)};
List<Vector4> closedNodes=new List<Vector4>();
int iteration=0;
List<Vector2> exploredCells=new List<Vector2>();
Vector2 resultCell=new Vector2(Mathf.Floor(endPosition.x*RegionHandler.chunkSize),Mathf.Floor(endPosition.y*RegionHandler.chunkSize));
Vector4 pathResult=new Vector4(0,0,0,-1);
while(openNodes.Count>0&&iteration++<2048) {
if(resultCell==new Vector2(openNodes[0].x,openNodes[0].y)) {
pathResult=openNodes[0];
break;
}
if(!exploredCells.Contains(new Vector2(openNodes[0].x,openNodes[0].y))) {
exploredCells.Add(new Vector2(openNodes[0].x,openNodes[0].y));
for(int i=0;i<4;i++) {
Vector2 moveDirection=new Vector2((i+1)%2*(i>1?1:-1),i%2*(i>1?1:-1));
Vector2 newPosition=new Vector2(openNodes[0].x+moveDirection.x,openNodes[0].y+moveDirection.y);
if(!walkableCells.Contains(newPosition)) continue;
float gCost=Mathf.Abs(openNodes[0].x-startCell.x)+Mathf.Abs(openNodes[0].y-startCell.y);
float hCost=Mathf.Abs(openNodes[0].x-resultCell.x)+Mathf.Abs(openNodes[0].y-resultCell.y);
float fCost=gCost*.25f+hCost;
openNodes.Add(new Vector4(newPosition.x,newPosition.y,fCost,exploredCells.Count-1));
}
closedNodes.Add(openNodes[0]);
}
openNodes.RemoveAt(0);
openNodes.Sort((a,b)=>a.z.CompareTo(b.z));
}
if(pathResult.w==-1) return null;```
i put rigid body on them is that ok
could anyone comment on how i could optimize this A* algorithm?
Anyway I have this flying lump, I tried to do it with acceleration, and its probably really really overly complex,
It sometimes has this weird bug where the movement will be really.. not smooth
here is my code https://pastebin.pl/view/14911c6b
heres the video https://www.youtube.com/watch?v=Vx9vLH2I1PE&ab_channel=Kloakk
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
you can see inconsistencies in the movement
around 13 - 15 secs in its rly obvious
i recommend you rewrite your code
you should use a Vector3 for velocity
help
also use a min max for your velocity i guess...?
and use += instead of currentVelocity=currentVelocity+acceleration*Time.deltaTime;
ah ok
hmmmmmmmmmmmmmmmmm
i would handle it with rotation too
wdym
basically something like
also deceleration from friction
is usually handled in factors
not with addition
can someone edit a script for me to set rotation for the object to the controller rotation (already included as gameobject bool) If yes dm me
basically
basically... use vectors?
Vector3 shipVelocity=new Vector3(0,0,0);
float acceleration=0.03f;
float decelerationFactor=0.98f;```
//accelerating
shipVelocity+=new Vector3(movement.x,movement.y,movement.z)*acceleration;```
blimey I have a lot to learn
where movement is a new Vector3
that you create
and set the x y and z to depending on the keys you use
0 is standing still
-1 is backwards
1 is forwards
repeat for all axes
ah thats why I was confused
can someone edit a script for me to set rotation for the object to the controller rotation (already included as gameobject bool) If yes dm me
then just position+=shipVelocity
stop
this might be a really dumb question right
yes
actually no it is
right
also i recommend rotating this Vector3
so you can rotate your ship
ah yeah, that was gonna be the next bridge to cross
mhm
whats your question
when you said do a vector3 for each axis I thought do 3 vectors3s
haha why
Vector3 is already three axes
its all right
how longve you been coding
reposted my question to #archived-code-advanced
Hey all, forgive me if this is the wrong spot to ask -
Created a 3D game, but need access to a Hexagonal Tilemap asset. The 2D GameObject menu is missing from my GameObject menu, of course.
https://docs.unity3d.com/Manual/Tilemap-Hexagonal.html
Having read online that you should be able to bring these into a project via a package import,
Anyone know where can I find the standard Unity 2D assets package so that I may do this?\
i guess
its literally
2d object>tilemap>hexagonal tilemap pointed top
in your context menu
are you using the last version of unity
I've spent a bit googling around for where I can find/download the 2D standard assets to no avail, I'm new, so I'm probably not referring to it correctly.
I've already said in the original question that it's not there, since this project was created as 3D.
hey sorry. on an off a couple years, but mostly off. Ill touch it, learn something, and not code for a good 4 or 5 months and have forgotten everything by then
wbu
create a 2d project...
This is not a project that was created by me, and it already has significant work done on it guys. I asked a specific question here about how to find the unity standard 2D assets so that I can import them into any project. If you guys don't know this, you don't have to respond
then explain that in your question
no need to get passive aggressive
theres a reason you cant use standard 2d assets in 3d projects btw
Having read online that you should be able to bring these into a project via a package import,
Anyone know where can I find the standard Unity 2D assets package so that I may do this?\
Note the original wording
where did you read this?
you can add them via the package manager I believe - create a temp 2d project to check which ones they are, there's a few
Sec, there was a post on the official forums I recall
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
what are you trying to do that isn't currently possible/available in the project?
Yeah, something must be up with my setup currently; I don't have many of the things the docs here show I should have. Saw this before coming to here as well
See original question: https://docs.unity3d.com/Manual/Tilemap-Hexagonal.html
you will need to download the 2D Tilemap Editor package via the Package Manager.
I'll see if I can't figure out why I can't see standard assets in my import dropdown then, signs point to that being a potential problem/fix
Unsure if any of this is is due to the fact this project is checked out from source control and some dotfile somewhere is being .gitignore'd, but my package manager has nothing in it.
Possible red herring, but I also don't see any scoped registries here in Project Settings, is this supposed to be populated?
I promise y'all I'm not trying to waste your time or be obtuse here
also i feel like this shouldve been in a different channel maybe
So, Anyone know why a characterController would return isGrounded false when I'm not moving but does return true if im moving and on the ground but even then sometimes it goes back and forth?

