#archived-code-general
1 messages · Page 220 of 1
System.Numerics.Vector3 might suffice? 
you probably could do that sure, but with my struct I can have custom methods to transfer it to unity's vector3 position and other custom stuff 😅
I thought the implicit cast could exist anywhere.
You can fix the local Json.net btw to work with Unity vector3 but You cannot do it on the Cloud Save because unity has access to that
you have to turn off ReferenceLoopHandling = ReferenceLoopHandling.Ignore
or else it gives you JsonSerializationException: Self referencing loop detected for property 'normalized'
Hello can i predict if car will hit other car or won't hit?
Yes you can
are they moving in straight lines at constant speed?
Gta2 ?
white car sliding/drifting . GREEN car moving along spline. speed and friction not constant
You have where the car is, and where the car just was. So you could just do an ugly raycast in the sliding direction. It won't be predictive (where you will be) but might be reliable enough for a game AI without needing to worry about the actual drift. Especially as the accuracy increases the closer you are to the vehicle. I'd probably use a cone trigger myself just to see if it's good enough before going any further.
it wont be this simple for what you wrote in the image, of raycast and use the brakes* if its not null. You need to consider the distance and how fast the other car is moving to see if they'll even be there by the time you can travel that distance
1 min i wlll record giff to show better what i mean
then it's going to be very complicated math
Hello! I have been working for the script below for about 30 minutes. I am new to using raw mouse position to aim things as I just learned it off the unity doccumentation 30 minutes ago. The script mostly works but as you can see in the video below, the back of the gun moves faster then t he front I asume due to something wrong with my Lerp, I want the whole gun to rotate as one but im not sure what I need to change. The second thing is the last part of the video where as you can tell when the gun is pointing forward and backwards, the tip is directly pointing at the mouse, but when its off to the side, its slighly off, how can I fix this, im running out of ideas. Thanks!
Code: https://pastebin.com/7QHvPsbj (its running on update just as an fyi)
Video: https://drive.google.com/file/d/1Psr0Jow1QMIJkPaFT0TGQM8D-IbKTMpw/view?usp=sharing
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.
The problem you're having is that you're interpolating the rotation and not interpolating the position. So it's moving directly to the place it should go but then slowly rotating towards the mouse.
Instead you should just interpolate the point it's aiming at towards the mouse, and then always have the gun directly aim at that mouse.
Ahhhh, that makes a lot more sense. Thanks.
Is there a way to use vector images in unity
I'd do something like https://hatebin.com/rfjwzfeigy
@leaden ice@lean sail@west sparrow thank you very much for advices , i can't record giff at moment ,but over all I've understood ideas and difficulties of this matter . thx again
Is there any way to covariate a generic List in such a fashion?
Dictionary<Type, List<Component>> components = new();
public List<T> GetComponents<T>() where T : Component {
return components[typeof(T)]; // this is an error obviously because List<Component> is not List<T>
}```
I can guarantee that the List<Component> in the dictionary will only contain that type, but of course I know the compiler cannot guarantee it.
So you want the Dictionary to contain inherited classes of Component?
Or why the hassle with the dynamic type
yes for example I have another method like:
void AddComponent<T>(T comp) where T : Component {
if (!components.TryGetValue(typeof(T), out List<Component> list)) {
list = new();
components[typeof(T)] = list;
}
list.Add(comp);
}```
The compiler seems to like this but I'll see if it actually works:
internal IReadOnlyList<T> GetPrefabs<T>() {
if (_byType.TryGetValue(typeof(T), out List<Component> componentList) && componentList.Count > 0) {
List<T> results = UnsafeUtility.As<List<Component>, List<T>>(ref componentList);
return results;
}
return Array.Empty<T>();
}```
this is using Unity.Collections.UnsafeUtility
but that's designed for structs AFAIK
https://github.com/SidiaDevelopment/generic-entitas/blob/main/Assets/EntityFramework/Entites/Entity.cs I have that here without returning a list, ill check if I can get it to work with a list 😄
See yeah it's easy enough to cast a single result
but (List<DerivedType>)listOfBaseType; is not something the compiler will cooperate with
and fair enough because there's no guarantee that there's not a different derived type in the list
public List<T> GetComponents<T>() where T : Component {
return components[typeof(T)].OfType<T>().ToList(); // this is an error obviously because List<Component> is not List<T>
}
Try this
Compiler doesnt complain, didnt test runtime though
Yeah that will definitely work the problem is it allocates a whole new list
which is what I'm trying to avoid
I guess I could always go the unity route
allocate by default
and provide a "noalloc" overload where the user provides their own list
Yeah that could work
Sorry if this is a stupid question but if I wanted to add a bunch of instances of a class to a list is the best way to do that basically just to hardcode them? im not sure how to phrase this better
private void InitializeSteps()
{
tutorialSteps.Add(new TS_ViewMainMonitor());
tutorialSteps.Add(new TS_CameraTutorial());
tutorialSteps.Add(new TS_ViewAnnouncementButtons());
tutorialSteps.Add(new TS_ABExplanation());
Debug.Log("Tutorial steps successfully initialized");
}
for example i have a class TutorialStep and in the TutorialManager i just have the steps hardcoded into its InitializeSteps method
seems unoptimal though
im pretty rusty so there might be some thing i'm forgetting that would make this easier or some unity feature im forgetting
maybe ScriptableObjects?
If you dont care about order you can get all of them via reflection and add them to the list
well I do need the steps to be in order
Then manually adding them is your way to go i guess
Hard to say without knowing what these methods return. But SOs being added via the inspector might work
do what works. if you're having an issue then only then worry about it
well my issue is i keep forgetting to add the steps in the tutorial manager script
idk what that means without context lol
sorry, the classes there are 'steps' to my tutorial, they're being added to a list
if i dont hardcode them into the tutorialmanager script to add them to the list like above then its pretty easy to forget
so id like it if they could just automatically be added somehow
but like sidia said i think its either reflection or nothing
just do it in the inspector
think i'd have to make em serialized then
yeah or use SO
hm. ill see about SO, hopefully not more work than it will save
if it was only a few steps it wouldnt be so bad but ive already wasted so much time just forgetting to add stuff
SO will just be a POCO as an asset pretty much.
what is a POCO?
Plain Old C# Object
like a class
if Monobehavior + c# object and asset made a baby you get Scriptable Object xD
hey guys is there a way to bake occlusion culling during playmode
using System.Collections.Generic;
using UnityEngine;
public class SFXTrigger : MonoBehaviour
{
public AudioSource playSound;
void OnTriggerEnter(Collider other)
{
playSound.Play();
this.gameObject.SetActive(false);
}
}
anyone know what part of this is making it play as soon as i start the game
i turned off play on awake
Debug.Log the collider that is triggering the trigger.
ohhhh
what do i remove?
You need to have a condition so it only plays when it hits certain things
Right now it could trigger on the ground
Or anything
mmm well i dont know how to script....
but its not touching anything i made sure of it
its hovering
You only have the trigger collider on the object? Or a solid one too? It could be triggering on itself
oh??
But what do you WANT it to trigger on?
Could do something liker:
if (other.CompareTag("Player"))
this is really helpful tho now i know what {
those
do
when like
{
}
The term for what they do is "scope"
They declare a scope that code belongs to.
The code inside those for an if statement only runs when the conditition is true, and is out of "scope" when false
what gets me is the capitalisation
if i miss one letter nothing is working💀
Don't have a semicolon after the if statement
i forgot to delete
Also, your !IDE is not configured it looks like
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
it didnt work before
oh?
Oh also, you need the curly braces {} for the OnTriggerEnter method
void OnTriggerEnter(Collider other)
{
if (condition)
{
//stuff
}
}
holy shit is this notepad++
S H U T U P i didnt change it to visual studio yet
lol
theme is wild
I strongly recommend doing it now
It will save you a LOT of trouble
ye
i am
wait
why cant i say
Try typing more than 1 word in your messages.
one
well sometimes i like to make a sentence that normal people can understand c:
It's a bot. We don't know what it's thinking... But probably because you sent a lot of one word messages in sequence.
idk
regex having a hard time rn
waht?
Point is: stop spamming and get to the point. Preferably in one message.
ohhhh yeah
how fix c:
fix what?
heres the og code
Does it still after the changes I suggested?
Show the current code, not og
And honestly, this should be in #💻┃code-beginner
You're supposed to be able to solve issues like that yourself if you are asking in this channel.
You almost already did.
The braces where just messed up. Fix like this
#archived-code-general message
ok
Also, config your ide before continuing.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
I suggest stopping and just doing this course real quick
https://www.w3schools.com/cs/index.php
It's not too long
this?
ok
i dont know what ide is?
You've been linked the bot message regarding it several times too.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
You don't need to repeat that...
mhm
is there a trick to handling duplicate types in different internal unity assemblies?
i.e. prioritize CoreModule ones, or something similar
what's the problem you're having with this exactly?
since you can have same type in different assemblies, yea, seems like the thing to do
depending on what you might want to do with them
FullName is always needed as you can definitely have same type in different namespaces (like Button)
If you want to cache all of them then then you need assembly as well like you mentioned
TBH it seems excessive and costly but i don't know your exact needs 😄
namespace + class name should be sufficient
im caching everything tools use once and reuse later, this one is for internal tools accessing unity internal types
the whole thing happens in one loop over all types and later used everywhere similar to fasterflect caching but slimmer
im aware mere fact of loading metadata that cant be dropped by gc is a downside, other than that its not noticeable
i have doubts but i cant pinpoint them
if you know why its bad please share, I want to know
full name already includes namespace and they clash
unity has a lot of duplicate namespaces and types in various assemblies
do you have an example?
sure give me a sec
UnityEngine.AnimationInfo , UnityEditorInternal.Transition, Microsoft.CodeAnalysis.EmbeddedAttribute
just grabbed from logs, there are hundreds
UnityEngine.AnimationInfo according to dnspy is present in 3 assemblies
one is an empty stub, one is from similarly named i assume legacy UnityEngine.dll, and one which just has attributes reordered is from UnityEngine.AnimationModule
It is, in fact, obsolete, are you checking the custom attributes?
obsoletion of this particular type doesnt mean others are
checking for it would mean the empty stub would be selected
no but it may cut down on your conflicts
im caching everything tools use once and
thats a local remedy for one particular issue with unthought ahead consequences
There is a particle system that has 5-6k particles and its simulation space is set to "World". I could move all particle's position one by one but Is there a better way?
Seems there is no other way.
Parent them and move the parent ;p
Im trying to edit the value of an InputField from within the editor. I'd like there to be a default value already in the InputField when it's shown. But the InputField doesn't allow me to do that. It rewrites itself to be empty every time. Is there a solution to this?
Yes sorry that one
If you want to show a placeholder value (e.g. "Enter text here...") that doesn't actually affect the user's input, you need to use the Placeholder field on the TMP_InputField
notice how the default Input Field object is set up
it has both "Placeholder" and "Text"
Placeholder isn't interacted with by the user. It goes away as soon as you enter any text.
But do you want to have a value that actually affects what the user inputs?
so if the field starts out saying "Name: ", and the user types "Bob", the result is "Name: Bob"?
No not really. I'll explain in more detail
The first time you play the game you need to enter a name. This name is saved in PlayerPrefs. Later, when you play the game again, instead of having the placehoder "enter name", I want the InputField to be already filled with the name that was saved in the playerprefs. But then if you want a different name you can still edit it
So I want to add text in the "Text" GameObject, but when I do that, it defaults back to being empty. The only way I can add text to "Text" right now is via the game itself, and not via a script
You don’t want to edit the text object itself
That’s being controlled by the TMP_InputField
Set the text property on the input field component
That’s also how you should be getting the result out, rather than reading it from the actual text component
Ah I get it. Thanks
InputField.SetTextWithoutNotify(NameFromPlayerPrefs);
Ah, good suggestion!
"Set without notify" means that any listeners won't be told about the change.
I used that to prevent a horrible infinite loop with my settings system + menu
yeah, usually better to use that instead just set the text in script
both will work better than trying to set the text component's contents, of course 😉
Are properties such as particle systems defined within an overall state machine or in the specific sub state scripts
@leaden ice lets say you have state machine and you are changing the colour of a cube and spawning a particle system dependant on each state
would i have in my overall StateMachine script references to each (aka _color1,2,3... & _particle1,2,3.. etc) or should i references them in the sub state scripts (aka in RedState script, public gameobject particleSystem, private color X.. etc)
Maybe neither? Probably in a ScriptableObject referenced by the state or something? Definitely not in the state machine orchestrator itself
Also if you find yourself with numbered variables you almost definitely want an array instead
can u prevent a variable from having its content copied when u Instantiate(<ExistingObject>) (cloning)
You can, watch Brandon-SGB poolmanger video he does it in there with the dictionary
No really ? But you can easily set it to the value you want afterward.
keep the data non serialized should work
hey guys ive been working with unitys XR toolkit and was wondering how to make something like this
what is "this"
an event ?
ye sorry, with this i meant a list(something like that) where i can put whatever gameobject on and use whatever method i want from it
omg thanks, just one last question... how would i trigger a function from that😅
nvm figured it out... its invoke
but thanks😁
make sure you use ?.Invoke
Do you need the null check on unity events? Not on pc but I vaguely recalling that you dont
its always good to check if has no listeners although I think unity does something diff with UnityEvent instead of regular C# event
hi is there any way to import a video clip and set it to play in the videplayer component. My project has config folder for which I'd like to be able to put a video clip into and have it play in the videoPlayer component. I heard it may be possible with either videoPlayer.url or using the www class but any advice would be great
ya was thinking this just as I wrote that lol..
I dont think I ever had a rull ref without listeners in inspector but don't recall
its been a while, I've ascended to C# ones xD
put the video into the Assets/StreamIngAssets folder and use UnityWebRequest to load it
What's the best way to go about having a character walk up or down some stairs?
in what sense ?
character controller + slope ramps
Well right now I'm using the input system, but the player character trips up on every little crack in the ground. Even when going up a ramp, its speed is dampened. I've seen stuff about rigidbody being able to do it, but I need to turn off gravity for it or something? I'm not sure I want to turn off gravity just for the character to be able to walk up stairs
oh so you're using a Rigidbody
to move a rigidbody up a slope you need to project its movement (the velocity or force being applied) onto the slope's plane. you can do this with Vector3.Project and getting the normal of the ground you are currently on
use the Kinematic Character Controller asset by Philipe St-Amand
still gotta project its velocity on the ground plane when using KCC, but it's an incredibly well made character controller
[Help] I'm trying to implement a Civ5 hex terrain
I have a random amount of enemies in my level. When the player kills all enemies I want to award a score of exactly 10000. How much score does each enemy award when killed? 10000 / totalEnemies.
But what if I want to add a combo system, for each enemy killed without getting hit the score awarded should by multiplied by how many enemies have been killed, maxing out at x10.
So, for killing every enemy I still want to award exactly 10000 points. How would the formula change?
Something like:
10000 / maxMultiplier / totalEnemies
But even in a perfect game, the first 10 enemies would award less points, so it doesn't add up correctly.
10000 / 10 / 20 = 50 score per enemy when we have 20 enemies in total, but I would get a score of 7750
What I have so far:
10000f / 10f / 20 + 290.323f / 20;
But this only works for exactly 20 enemies, I somehow need to calculate that 290.323f number
Thank you @rigid island @somber nacelle @polar marten
wassup guys
i need some help on doing a top down system, just like enter the gungeon
but i wanna make a horror game from it
i'm having difficult on doing the flashlight, and making it point towards my mouse
2D or 3D
show script
2D
i'm not on my pc with the project :(
then how we supposed to help?
make the rocket Kinematic or freeze Rotation
with a sugestion, maybe. a directionfor me to follow
as I said it doesnt works properly
rotation also
alr so just use the kinematic approach then
this way you can push other rigidbody but they cannot affect you
kinematic doesn't react to external forces
when kinematic is turn on, the rocket doesnt fly
whats wrong with that solution?
is it possible to enable and disable effects on audio mixers at runtime via code?
I know you can crank down the value so that there's practically no effect but if I have to resort to that I'm worried there will still be processing
rocketRb.MovePosition( transform.up * speed)
sorry my cat stepped on my keyboard there lol
anyways i've read that it's not actually possible to enable and disable effects on audio mixers at runtime, is there a way to make the audio muffled when my car goes underwater without taking a performance hit?
I think MovePosition uses world pos
its been a while
lete me see
try rb.MovePosition(rb.position + ( transform.up * speed) );
hello. i want to achieve the following: whatever the game state is, I want to persist it asap, so the player cannot undo any actions taken or something. how do I achieve this? I assume the persisence needs to be done either on a different thread or with async (?). how do i prevent the game from hanging whilst the write happens? how do i prevent race conditions while writing to the file? any help is appreciated. thanks!
PS: the persistence itself i want to do locally in json via json.NET
Odds are people aren't going to exploit it if you just save immediately
simple Json Async
I'm setting my mesh vertex buffer with a Native Array, but the issue is I need to pre-specify the number of vertices contained in the native array, and I'm procedurally generating meshes where vertex count in unpredictable
I can't append to a native array like i can to a list, so should I set vertex count to the max and limit the range of the array that's copied into the mesh vertex buffer, or something else?
What's the best way to handle this?
I set vertex count to the max and limit the range of the array that's copied into the mesh vertex buffer, or something else?
sure. presumably you need to know the size at some point. so why not bind the vertex buffer then?
Does anybody know if there is something like a callback for a particle system's emission bursting? I have one that bursts randomly and I'd like to sync up a sound effect to it.
I wasn't able to find one in the docs
By binding you mean mesh.SetVertexBufferData() yeah? I do that after all my vertices have been generated anyway
One thing I could do is store vertice information in a list, then when setting the vertex buffer I can convert it to a native array
But that sounded like a slow solution to me
SetVertexBufferData() has index start and end value so I thought itd be a pretty clean solution to set the native array to max length if that doesnt impact performance severely
It all deppends on the size, if its a small mesh performance wont change that much on either method.
If its a big mesh, allocating more, you are wasting video memory.
If you want the fastest, its by knowing your size, allocating exactly that and filling it.
Other way put into a List and set by Mesh.SetVertices(list).
If are changing the mesh frequently, maybe waste memory to gain performance. If you are changing the mesh once in like 10 seconds, do the "less" performant way, save memory. You can also set the List<T> initial capacity to avoid reallocating while adding items in it.
Hi, I have a curve made out of points and I want the points to move/rotate/scale relative to the object's transform, so in order to do that, I use transform.TransformPoint(vertices[i])
Right now, I store the initial point positions in a second list, but I am wondering if there's a better way to do it, without having to have a second list of the initial point positions
Here's the code:
public List<Vector3> vertices = new List<Vector3>();
public List<Vector3> verticesInit = new List<Vector3>();
private void Update()
{
if (!transform.hasChanged)
return;
for (int i = 0; i < vertices.Count; i++)
{
vertices[i] = transform.TransformPoint(verticesInit[i]);
}
transform.hasChanged = false;
}
void OnDrawGizmos()
{
if (vertices == null) { return; }
if (vertices.Count == 0) { return; }
for (int i = 0; i < vertices.Count; i++)
{
Gizmos.color = Color.red;
Gizmos.DrawWireCube(vertices[i], new Vector3(0.5f, 0.5f, 0.5f));
Gizmos.color = Color.white;
if (i < vertices.Count - 1)
Debug.DrawLine(vertices[i], vertices[i + 1]);
}
}```
Isn't there another way, maybe storing the previous Transform data from the last time the transform changed?
Apparently they can use the same list to read and write from. (Scratch that, i'm wrong). You could also instead of transforming on update, transform OnValidate
Unless its ok to lose the initial data ? If dont keep on separate lists, you'll be transforming twice the same unchanged points
if I use the same vertex list (vertices) like so: vertices[i] = transform.TransformPoint(vertices[i]); see what happens on the video
I don't plan to use OnValidate , because I need to do this in runtime
Yep, they are transforming twice, you need two. Make a function to notify when changed, set also OnValidate to call that function
I think if I wanted to use only one vertex list, I would need to store the Transform data of the previous transform change, like substracting the current Transform by the Transform before it is changed, not sure if this makes sense
Feels overcomplicated...you'll be "untransforming" to transform again.
You could also manage your points through functions, AddPoint and SetPoint. This way every point you change, you already transform it correctly, them you can have one list and you only add to that list after you safely transformed
Have a second list for the editor only, keep a single private list for the runtime (and editor), change the list through access functions
Sounds good, gonna try that, thanks!
also, would it be better to create an event for when the transform changes, rather than using Transform.hasChanged? would an event make less calls? idk
The problem with Update, its being called every frame, but sometimes not executing. You should only use if you need something called every frame. Having a "callback" function is better, you are only calling it when a change occurred.
Or maybe, keep the original points and transform once you need to read it ?
this way will always be fresh
right, I guess i'll only check for transform changes if the object is selected
thanks a lot, great help 👍
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
//currentMovement.x = moveDir.x * MoveSpeed();
//currentMovement.z = moveDir.z * MoveSpeed();
controller.Move(moveDir.normalized * MoveSpeed() * Time.deltaTime);
}
controller.Move(currentMovement * Time.deltaTime);```
how do i fuse the controller.Move functions into one thing. Im not that good at vector math;
is there a way to make GetContacts get contacts as of right now? ie if I move the rigidbody, the contacts don't seem to update when I GetContacts on the collider
pretty sure Contacts are not updated until the physics is simulated
like that, but it doesn't seem to update until physics update
I figured, but is there a way for me to get similar information then? My challenge is that I might have one collider touching another with two very different angles (ie player touching a floor and wall of same collider)
which version of Unity added delta compile in IL2CPP? 2020 seems to recompile entire project even on scene change.
I can call OverlapCollider, then Distance. And that gives me like 90% of the same information as GetContacts (that I need). But I'm missing the potential to detect contact with a collider at multiple angles at once.
I want to avoid casting the whole shape 4 times: up/down/left/right to check for directionality
howdy, does anyone happen to have any good documentation about setting up a finite state machine for movement / character controler?
i just use an enum tbh
pretty much this ^
and make some values in the enum that combine others
I was looking at GTA III source code translated to C++
Surprising the amount of enums they used back then
like:
Neutral = 0,
Jumping = 1,
WallJumping = 2,
MidJump = Jumping | WallJumping
}```
and you want to use those mixed ones so you don’t need to screw with logic if you add more state in future
eg Swimming, Bouncing…
ok, so I have a plan to get contacts that I need for grounding, but I think it might be inefficient
basically, cast up/down/left/right (restrict to directions that are needed) once per physics frame per thing that needs contact information
then make a struct that simulates contactpoint2D, but with fewer fields
then make a function that returns IEnumerable<ThatStruct>(Collider2D collider), to just enumerate out information about individual information from single hits. Use this method to populate a ContactState struct
Does this sound like a good idea? Or is there maybe a smarter way to do this?
Hello! This is a follow up question from yesterday. I have been working for the script below for a while. I am new to using raw mouse position to aim things as I just learned it off the unity doccumentation yesteday. The script mostly works but as you can see in the video below, when the gun is pointing forward and backwards, the tip is directly pointing at the mouse, but when its off to the side, its slighly off, how can I fix this, im running out of ideas. The second thing is the last part of the video where I start to move my player around, but as you can see when I move the player the mouse desyncs from the mouse and im not sure why. Thanks!
Code: https://hatebin.com/wtyodjdyqs (its running on update just as an fyi)
Video: https://drive.google.com/file/d/1J1zHwpeBK_wXp-vJi4o6kmLkMw9clSYs/view?usp=sharing
Upgraded to Unity 2023.2.0b16 and for some reason my forms code isn't displaying the dialogue anymore. Dialog result always returns "Cancelled"
Not sure if there's been a change in how ShowDialog needs to now function or just a general bug with the version
Any idea what the deal is here?
Do you have the
using System.Collections;
hey gang, im getting this error. i can run my scene just fine. but i have no reference to where exactly this is having issues, except that "at <bf6080dbf0564cf1b405dfd6e0dac725>:0" which idk if its like an object code i can search for or something
What's the error description?
added it, still persists
you mean this bottom part?
Try using transform look at
https://docs.unity3d.com/ScriptReference/Transform.LookAt.html
Yes, it seems like unity is trying to close your inspector when it's already closed. Maybe your layout is broken? The layout button in the top right corner.
Isnt that going to be a complete different method?
Like Im following a tutorial and if we switch that isnt everything going to be confusing
Technically yes, but it's the newer version of the statement. It just uses a transform variable and rotates the object to look at it which I believe is the same as the look at statement but I would maybe check the docs.
did you define something named Quaternion, maybe it is trying to use the wrong type then? Otherwise show your full code
kinda feel like an old person. reseting didnt do it but then i was like "hold on i dont think i've tried closing and opening unity since i started gettting the problem yesterday"
needless to say, its fixed now 👴
thanks for the help
Happens to the best of us, I was just about to recommend that to you but glad you figured it out!
yeah when you mentioned windows being closed but not actually closed it kinda clicked lol
This was the issue
I was confused when I tried some other ones, deleted it and fixed it
Always funny when you fix something flick back over and someone literally gave you that advise
Thank you
thats typically what that error will come down to
Rad, well yall are in here, any tips on what to add to a Targeting Camera so it doesnt disappear behind walls XD
The first unity guide i watched made state machine using polymorphism. 
Like I used a collider on my other one
this would be a question for #🎥┃cinemachine
oooh neat
what does that do with LookRotation?
Its the using statement that contains the LookRotation statement.
no it isn't
LookRotation is a method on the Quaternion struct which-of course-is in the UnityEngine namespace
Could have sworn it was in the collections, but now that I think about it that makes a lot more sense.
huh? that's a Unity API method as Quaternion is a unity struct . . .
The Quaternion he's using is probably from System.Numerics.
well that quaternion implementation does not have a LookRotation method. nor is it in the System.Collections namespace
or are you referring to the person who originally had the issue?
This.
Yeah.
Yeah probably should have read more.

i dont understand why this isn't working.
IEnumerator HandleNPCsTurn()
{
if (npcList.Count == 0) yield break;
NPCStateManager currentNPC = npcList[currentNPCIndex];
Debug.Log($"Handling turn for {currentNPC.gameObject.name}, IsTurnInProgress: {currentNPC.IsTurnInProgress()}");
if (!currentNPC.IsTurnInProgress())
{
currentNPC.TakeTurn();
yield return new WaitWhile(() => currentNPC.IsTurnInProgress());
}
else
{
Debug.Log($"{currentNPC.gameObject.name}'s turn is already in progress.");
}
// Move to the next NPC
currentNPCIndex = (currentNPCIndex + 1) % npcList.Count;
// Log the next NPC
if (currentNPCIndex < npcList.Count)
{
Debug.Log($"Next NPC in turn: {npcList[currentNPCIndex].gameObject.name}");
}
if (currentNPCIndex == 0)
{
tod.AdvanceTime();
DisplayEndOfTurnMessage();
}
}
public void TakeTurn()
{
Debug.Log($"Attempting to take turn for {gameObject.name}");
isTurnInProgress = true;
StartCoroutine(SimulateTurn());
}
private IEnumerator SimulateTurn()
{
Debug.Log($"Simulating turn for {gameObject.name}");
yield return new WaitForSeconds(1);
// After the delay, end the turn
EndTurn();
}
public void EndTurn()
{
isTurnInProgress = false;
Debug.Log("Turn ended for " + gameObject.name);
}
I have two GO's in the scene the first one cycles through all the methods. The second GO Stops at TakeTurn()
Handling turn for NPC (3), IsTurnInProgress: False
Attempting to take turn for NPC (3)
Simulating turn for NPC (3)
Turn ended for NPC (3)
Next NPC in turn: NPC (2)
debug log ^
Any idea why its stopping?
I'm gonna tell you a secret. You must not share that with anyone. Understood ?
Is the object running the coroutine getting disabled?
no, it is not
huh?
Statemachine
That going to explain why It's not continuing?
That is going to make so you never ever need to even think about it.
Wouldn't I still need the HandleTakeTurn ? to cycle through the list of all the gameobjects then call their states? I watched some youtube videos on fsm and I had one implemented maybe not in the write way and It was doing the samething so I dumbed it down so I could make it easier for me to read.
Ok. I see. The coroutine ends after processing one npc, which is expected according to that code.
Each NPC would handle its state. It might be turning, walking, jumping, talking whatever they are doing.
You would just have to say: Hey, you, NPC 23, can you turn towards that ?
It's stopping because it run all the code. If you want it to run from the start again, you'll need to start it again.
That or have a loop inside the coroutine.
thank you, I added a while loop into the coroutine and it is working properly
@steady moat
public enum NPCState
{
SeekingFood,
SeekingWater,
Resting,
Idle
}
private void CheckNeeds()
{
if (squareNPC.hunger < 20)
{
currentState = NPCState.SeekingFood;
}
else if (squareNPC.thirst < 20)
{
currentState = NPCState.SeekingWater;
}
else if (squareNPC.energy < 20)
{
currentState = NPCState.Resting;
}
else
{
currentState = NPCState.Idle;
}
}
switch (currentState)
{
case NPCState.SeekingFood:
Debug.Log($"{squareNPC.name} is eating. Skipping turn.");
EndTurn();
break;
//aiMovement.UpdatePath(foodSourcePosition);
//StartCoroutine(WaitForPathAndMove());
//break;
case NPCState.SeekingWater:
Debug.Log($"{squareNPC.name} is Drinking. Skipping turn.");
EndTurn();
break;
//aiMovement.UpdatePath(waterSourcePosition);
//StartCoroutine(WaitForPathAndMove());
//break;
case NPCState.Resting:
Debug.Log($"{squareNPC.name} is Resting. Skipping turn.");
EndTurn();
break;
case NPCState.Idle:
Debug.Log($"{squareNPC.name} is idle. Skipping turn.");
EndTurn();
guessing i did this wrong?
Yes it is wrong. You gotta use polymorphism which you havent.
ok, ill rewatch the video. ty
However, I see what you are trying to do and I think that you are mixing 2 things together. The strategy and the state of the agent. You would really benefit from reading on GOAP as well of Statemachine. https://learn.unity.com/project/goal-driven-behaviour?uv=2021.3&courseId=5dd851beedbc2a1bf7b72bed
ty!
Method that returns IEnumerator. It's completely fine to use it instead of IEnumerable?

If it's a coroutine, you NEED to use it afaik. You'll get an error for IEnumerable iirc
What specific situation are you talking about?
Maybe returning an enumerable collection since that's i find myself using yield most. I don't use coroutines.
foreach(string str in items)
{
itemSaveData itemSaveData = JsonUtility.FromJson<itemSaveData>(str);
item itm = transform.GetChild(i).GetComponent<item>();
itm.items = new List<item>();
int I = 0;
foreach (int itemId in itemSaveData.itemIDs)
{
itm.items.Add(itm);
if (itemId != -1) itm.items[I] = transform.GetChild(itemId).GetComponent<item>();
else itm.items[I] = null;
I++;
}
Debug.Log(itm.items.Count);
i++;
}
The debug.log returns the expected size of the list but the list is completely empty in inspector
Empty as in having a size of zero or having empty elements of the correct size?
size of zero
In the above, you've logged the size of itm.items
and it returns the correct size
Is that the collection that you're looking at?
yes
Can you verify this with an image?
{"pos":[-0.04549373313784599,0.7342511415481567,0.7789515852928162],"rot":[1.7644731998443604,31.65037727355957,89.97978210449219],"isKinematic":false,"saveInts":[0],"saveFloats":[0.0],"saveStrings":[""],"itemIDs":[-1],"objectCode":0}
Json data for the item
wait
Is this the only child with the item component?
Log other important stuff as well like the name of the object with the list
I did that and it was correct
Or the name of each item being added
I'm unable to verify. If the logs are correct, the collections should be correct.
at the moment the item ids being added are -1 as I want it to be empty
This line looks weird btw itm.items.Add(itm). Referencing itself
I was trying to fix it in weird ways
I heard you can't add nulls to a list so i just add itself to the list (as its also an item) and then just set it to null afterwards
Sure you can..
foreach(string str in items)
{
itemSaveData itemSaveData = JsonUtility.FromJson<itemSaveData>(str);
item itm = transform.GetChild(i).GetComponent<item>();
itm.items = new List<item>();
foreach (int itemId in itemSaveData.itemIDs)
{
if (itemId != -1) itm.items.Add(transform.GetChild(itemId).GetComponent<item>());
else itm.items.Add(null);
}
if(itm.items.Count > 0)
{
Debug.Log(itm.objectCode);
Debug.Log(itm.items.Count);
}
i++;
}
changed it back to this but it is still not working
it is the only item with that object code
I'm assuming itm.items is simply empty. This would occur if itemSavedData.itemIDs is empty
how would itm.items.count return 1
If there were one element
so itemsavedata.itemIDs cannot be empty as for it to have one element it would have to have been added in the foreach(int itemId in itemSaveData.itemIDs)
So we don't know that unless you logged that (the result)
If it's empty or one, that would be all that you would get
foreach (int itemId in itemSaveData.itemIDs)
{
Debug.Log("item ids is not empty");
if (itemId != -1) itm.items.Add(transform.GetChild(itemId).GetComponent<item>());
else itm.items.Add(null);
}
Why not just print the size?
Your itm.items should theoretically yield the same result unless overwritten elsewhere
itm.items = new List<item>();
foreach (int itemId in itemSaveData.itemIDs)
{
if (itemId != -1) itm.items.Add(transform.GetChild(itemId).GetComponent<item>());
else itm.items.Add(null);
}
Debug.Log($"itemIDs is size {itemSaveData.itemIDs.Count}");
if(itm.items.Count > 0)
{
Debug.Log(itm.objectCode);
Debug.Log(itm.items.Count);
}
So one itemIDs thus why you got one item
just checked that by only saving and loading the one object, its the same.
I also know the item script isn't setting the size to zero as if I disable the script on instantiate it has the same issue
Debug.Log($"{itm.name} has a count of {itm.items.Count}", itm);```
I suggest you use the debugger and step through this function. Either you're overwriting the list elsewhere or you're looking at the wrong object. It's a pretty simple process.
Figured it out
at the beginning of my void I would destroy all children but instead of destorying the transform i was destroying the gameObject. that meant that transform.getchild or transform.childcount was not correct
no nvm
didn't work
destroying transform didn't get rid of the object so I just got the childcount at the start of the void and added that to the index'
Does anyone know why objects have the blue navmesh walking path on the tops of them?
you have meshes there?
the object has a mesh renderer
and mesh filter
It's just basic cubes streched and moved
Thank You
you can also reduce the step height on your agent to make those tops out of reach
Respected,
can you please guide how can i add ratemyapp feature in android and ios unity build?
Google review page without leaving the game.
Thanks
Hey guys!
I am working on an AR app for Google Play store and Apple app store and it is huge as it includes a lot of 3d models and meshes.
I tried using the Play Asset Delivery Package to create my App Bundle but the Upfront Asset Pack created is larger than 1GB which is the limit.
Can someone help me with this? I have already completed development and just need to publish now.
So I am trying to switch Two Bone IK Constraint targets when I switch the gun and its switches but the hands stay the same. Anyone know why or what I can give you to help?
nvm
hi
public List<List<Collider2D>> levels = new List<List<Collider2D>>();
public List<Collider2D> level0 = new List<Collider2D>();
public List<Collider2D> level1 = new List<Collider2D>();
public List<Collider2D> level2 = new List<Collider2D>();
public void DisableAllLevels()
// {
// foreach (List<Collider2D> level in HeightManager.heightManager.levels)
// {
// foreach(Collider2D col in level)
// {
// Physics2D.IgnoreCollision(physicsCollider, col, true);
// }
// }
// }
I have this script and the way I want to do it is so that for every collider in each level, I want it to ignore the collision of every collider in level 1 with every collider in level 2 and I want to do this for all levels. here I've simplified it down to 3 levels but there will likely be more so how could i do this. this was hard to explain so ill understand if you don't get what i mean
Cant you just use layers for that?
there could be loads of levels i feel like it would clog the matrix
are you loading all levels at the same time or just 2-3?
all at the same time
Can you talk about what you want to achieve with this?
maybe there is a different approach
so its basically a fake height system and the way i have it setup rn is that the player themselves changes what colliders are ignored and which arent
but i want another script to do it because it would be more practical with what i want to do
What collider information do you need that you're splitting it between levels like this
such that are you raycasting onto these colliders or is there some proximity info you need from around a gameobject
Seems like a situation where you need some z-depth to accomplish, otherwise dynamically switching layers to ignore them when you surpass the limit.
I would just disable all colliders of the height the player is not on
this is what i did last time but it would be impractical if the player had multiple colliders which is what i want
I dont understand why thats a problem
because the multiple colliders would be at different height levels so i couldnt just base it all around one collider
then enable all colliders on which level the player has a collider
Is it possible to intergrate a unity game into reactnative?
it would be easier to use one manager script is what im saying
You can export a build as an android project
what about ios?
public List<List<Collider2D>> levels = new List<List<Collider2D>>();
public void DisableAllLevels()
{
for (int i=0;i< levels.Count;i++)
{
List<Collider2D> first = levels[i];
for (j=0;j<first.Count;j++) {
for (int k=0;k<levels.Count;k++)
{
if (i == k) continue;
List<Collider2D> second = levels[k];
for (int l=0;l<second.Count;l++) {
Physics2D.IgnoreCollision(first[j], second[l], true);
}
}
}
}
}
ty ill try it
yeah that works ty a lot
is there a way to make the contents of a collection accessible as read only to other classes?
Make it a property with a private setter
eg if i have
public List<int> myList {get; private set;}
If I do this, the class holding myList can set the whole myList variable, and I expose myList for other classes to see. But I accidentally expose the list to being altered by other classes by Add/etc
IReadOnlyXXXX interface
i see. and I can only do this with custom classes then, right?
it would be theoretically nice to have access modifiers or attributes to mark certain methods as ones that can mutate instances, to be able to lock them away.
but i guess that’s not in the language
ty for the input, tina
Follow-up question: If I have Class1 and Class2 both in namespace MyNameSpace, but in different files, the internal keyword allows them to expose things to each other, but not to classes outside of MyNameSpace?
huh, actually, now I'm really confused looking at my other code
Hello, does [field: SerializeField] change any behaviour of the simple public title (non property) ?
[field: SerializeField] public string title { get; set; }
yes
are you talking to me? how?
title is a property. you can't serialize a property
no, you can
no you cannot
using the method I showed above, you can
you cannot serialize a property
title is a propery with an auto-generated backing field
the property title is serialized in the inspector now
you can serialize the auto-generated backing field, which will look something like k_title
that is what you can serialize
so if you do
[SerializeField] public string title {get; set;}
You won't serialize anything. because title isn't a field. it's a property
so you can't save its value, and you won't see it in inspector
yes, but I am referring to [field: SerializeField]
but if you add [field: SerializeField], then now you are actually targetting the backing field which is autogenerated
which you can serialize
and you can see in inspector
that is the difference
ok, I get what you're talking about now
but does it affect the property in the negative way?
I still can access it and assign in the inspector, right?
SerializeField doesn't touch the property. it can only affect the backing field
the property is however you defined it
you can never access a property in inspector
modifying it in inspector changes the value of the backing field
I see, so basically this
[field: SerializeField] public string title { get; set; }
is similar to this?
[SerializeField] private string m_title;
public string title { get; set; }
uhhh almost
fyi,. you can do something like this:
[field: SerializeField] public string title {get; private set;} = "Untitled"
why would I?
ye
[field: SerializeField] public string title {get; private set;} = "Untitled";
This is the same as:
public string title { get {return m_title;};
private set {m_title = value;}; }```
Oh, well, yeah, I forgot about it
this is a very common and useful pattern
that's what I meant
yep, just forgot it
anyway, using field: you can change neither get nor set
it makes title's backing field appear in inspector to be editted, allows the class to change the value of the backing field, exposes the backing field in a read-only way to external classes
you can do private set
yep, but you cannot change its return
[field: SerializeField] public string title {get; private set;} = "Untitled";
This is a very common pattern you should memorize.
sure
thank you for your explanations 😄
if you make your own custom get/set with actual logic, then you want to define your own backing field
I use the backing field serialization everywhere but someone was saying if you want to rename the variables it kinda breaks the serialization
I know, it's just really annoying when you have more than one field
rather, gotta point to the location of the field and it's a pain
annying with just one too though
eg
public string title { get {return m_title;};
private set { Debug.Log("New title = " + value); m_title = value;}; }```
yeah, if you rename the simple serialized variable, its value will be lost
well, yeah. you changed it lmao
so in a sense it is better to just seperate the field if possible if you don't mind the clutter
could someone explain the internal keyword to me? I'm confused as to when an assembly starts and ends
quite hard when I do mind.
I'm too tired at this point and I need some help. I have this piece of code
if((distance > d.shadowFadeDistance) && (dot < 0) )
{
// Debug.Log($"Distance to light:{t.name} is:{distance}");
if (!evictedLights.ContainsKey(i))
{
shadowManager.ForceEvictLight(d);
evictedLights.Add(i,d);
// Debug.Log($"Evicted {t.name}");
}
}
else
{
if(shadowManager.WouldFitInAtlas(d))
{
if (evictedLights.ContainsKey(i))
{
Debug.Log($"Distance is:{distance} shadow fade distance is:{d.shadowFadeDistance} and dot is:{dot}");
shadowManager.ForceRegisterLight(evictedLights[i]);
evictedLights[i].RequestShadowMapRendering();
Debug.Log($"Requested rendering for {t.name}");
evictedLights.Remove(i);
}
}
}``` Yet I get this debug log ```Distance is:133,9301 shadow fade distance is:100 and dot is:71,9750``` how can Distance be > than shadow fade distance and yet hit the else statement
Yeah, but you can't just easily slap this on it like you'd usually do
https://docs.unity3d.com/ScriptReference/Serialization.FormerlySerializedAsAttribute.html
&& dot<0
myAssembly.dll
the DLL is the whole assembly
Well yes its AND not or or am I being incredibly strudip
I have not been making any assemblies actively
eg this explains is a bit better than I could Lol
https://docs.unity3d.com/Manual/ScriptCompilationAssemblyDefinitionFiles.html
if dot is >= 0 then it goes to the else regardless of what the distances are
I see. so it takes more effort to really define an assembly to properly use the internal keyword
encapsulation basically
So how do I stop it short-circuiting
all it comes down to
yeah its not very often I see internal but its useful I suppose when you dont want to expose class/method in other libraries and cause conflicts but still keep it public/ visible to the DLL/Library its in
What do you actually want it to do? If you want either of those be true then use ||
I want both of them to be true and not true for the else
What do you want to happen if one is true and the other is false?
nothing
== ?
you need else if
else if(distance <= d.shadowFadeDistance && dot >= 0)
thank you guys
ok, I need a bit of help. I need the ability to check a collider making contact with another collider at multiple points of contact with different normals.
Easier to show through images but I'm on phone sad.
Just the entire scope of the [C#] icon in the solution explorer is the entire assembly.
Red circle touches blue collider at multiple points with different normals, and I need to know this.
GetContacts would work, but the result only updates at the last physics simulation.
.Cast only gives one RaycastHit2D per collider you hit
Raycast is going to be more difficult to do right, because I need good knowledge, and the curved edges of a boxcollider are a problem
Any suggestions on how to know the points of contact for the red circle?
What exactly is wrong with GetContacts?
I am making a custom physics simulation, so I'm moving my rigidbody around. And I need to know my contacts as they exist after the RB has been moved
so if I just moved my red circle from somewhere else, GetContacts is totally wrong
Would this suffice? https://docs.unity3d.com/ScriptReference/Collider.ClosestPoint.html
Not exactly sure how well this implements with multiple points at once
Rather I'm not too sure how you're grabbing the points in the first place with the circle relative to the blue bounding wall.
Are you planning on some sphere cast methods or such?
closestpoint would work if there were multiple colliders that made up the segments here, but if this is like some custom collider or mesh then that makes it a bit more difficult
^ because you can grab all surrounding intersecting colliders of each and find the closest point of each
.Cast for te most part
the problem is that I am touching a tilemap collider, which is one collider with complex shape
so I could have a flat and slope, and the player's one collider could be touching both a slope and flat segment at once
so I need to know what is being touched.
I'm not too sure with a custom mesh collider if that's the idea, or that this blue collider is a single segment because this then requires some vertex navigational logic to find each intersection.
GetContacts actually does a lot of this extra logic for more complex colliders which is why it's handy
If you slice the blue collider up into multiple sections, then you can get a point per collider which makes it somewhat easier.
Since it's 2D, maybe it's less technical than I'm thinking.
also, I realize for casting a BoxCollider2D, it's very similar in cost to a single 2D raycast of same distance
I was reading that unity cheats with math when it comes to more triangle heavy colliders like sphere and capsule when it comes to collisional checks.
I see
well, I still have the challenge of discriminating these two
and knowing I have those two normals.
If it's two different colliders (the blue walls) you get the closest point and you can get the normal from those
one collider. blue collider is one piece
because it's a tilemap
and it would be a really bad idea to split my tilemap collider into 1000's of individual colliders
Spheres and capsules aren't really treated as meshes with triangles in physics engines, they are mathematical functions. Therefore way cheaper than a mesh collider
A cylinder will be expensive yeah, because it has to be a mesh collider since it doesn't exist as a primitive
Ah, makes sense
someone here is patient enough to explain to me how to code a system for importing - exporting character data (head, hair, clothes etc ) like the gacha club system (in dm)
Nothing special about this really, it's the same as any saved game system
- identify the data you want to save
- collect all that data in one place (a class for example)
- write code that turns that class into text (JSON is quite common. In your screenshot it looks like a custom format)
- write code that can take the text and give back the object (same thing as the previous step just backwards.)
- voila now you can convert your in-game stuff into a string and back
this is called Serialization and Deserialization
you can skip most of the "write code" parts of that by using off the shelf serialization frameworks
Hello, does somebody know why my class is saved in Json in this format?
"itemsData": [
{
"<title>k__BackingField": "Ground 3",
"<name>k__BackingField": "Ground",
"<itemType>k__BackingField": 2,
"<collisions>k__BackingField": 121
}
]
ItemData class: https://gdl.space/ohoyagimen.cs
looks normal
that you're serializing the backing fields?
when you use an auto property the fields are named like that internally
sure, it doesn't change normally since I've added [field: SerializeField]s
depending on which serializer you use, you can change it with annotations typically
wdym "it doesn't change normally"?
I mean that position and rotation properties aren't included there, even through they should
they are not serializable because they're properties
oh.
notice you have [field: SerializeField] on the other properties?
You would have to add that to these to serialize them too
I thought it's just for the inspector, well, I see now
the inspector uses the same serialization mechanism that JsonUtility uses
but what do I do if I want to make them invisible in the Inspector, but visible in the json file?
[field: SerializeField, HideInInspector] ?
yes
Can anyone help me understand why I am only receiving positive numbers for movement in the animator? Regardless of if I hold A or D, the number only ever goes to 90 and acts like I am trying to turn right
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 movementDirection = new Vector3(horizontalInput, 0, verticalInput);
// float inputMagnitude = Mathf.Clamp01(movementDirection.magnitude);
float inputMagnitude = movementDirection.magnitude;
float angle = Vector3.Angle(Vector3.forward, movementDirection);
// Checking which leg is up
if (rightFoot.position.y > leftFoot.position.y)
{
isRightLegUp = true;
}
else
{
isRightLegUp = false;
}
// if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
// {
// inputMagnitude /= 2;
// }
movementDirection = Quaternion.AngleAxis(cameraTransform.rotation.eulerAngles.y, Vector3.up) * movementDirection;
movementDirection.Normalize();
animator.SetFloat("InputMagnitude", inputMagnitude, 0.05f, Time.deltaTime);
animator.SetFloat("InputDirection", angle, 0.05f, Time.deltaTime);
animator.SetBool("IsRightLegUp", isRightLegUp);
positive numbers for which parameter?
You mean this?
float angle = Vector3.Angle(Vector3.forward, movementDirection);1```
Vector3.Angle only returns positive numbers
Why is this Coroutine not working? The delay is not applied at all:
private IEnumerator PaintSingleTileWithDelay(Tilemap tilemap, TileBase tile, Vector2 position)
{
var tilePosition = tilemap.WorldToCell((Vector3)position);
tilemap.SetTile(tilePosition, tile);
yield return new WaitForSeconds(tileDrawDelay);
}
internal void PaintSingleBasicWall(Vector2 position, string binaryType)
{
int typeAsInt = Convert.ToInt32(binaryType, 2);
TileBase tile = typeAsInt switch
{
_ when WallByteTypes.wallTop.Contains(typeAsInt) => wallTop,
_ when WallByteTypes.wallSideRight.Contains(typeAsInt) => wallSideRight,
_ when WallByteTypes.wallSideLeft.Contains(typeAsInt) => wallSideLeft,
_ when WallByteTypes.wallBottom.Contains(typeAsInt) => wallBottom,
_ when WallByteTypes.wallFull.Contains(typeAsInt) => wallFull,
_ => null
};
if (tile != null)
StartCoroutine(PaintSingleTileWithDelay(wallTilemap, tile, position));
}
And why does it work here?:
public void PaintFloorTiles(IEnumerable<Vector2> floorPositions)
{
StartCoroutine(PaintFloorTilesWithDelay(floorPositions, floorTilemap, floorTileData)); // DELAY
IEnumerator PaintFloorTilesWithDelay(IEnumerable<Vector2> positions, Tilemap tilemap, TileTypeData tile)
{
foreach (var position in positions)
{
PaintSingleTile(tilemap, tile, position);
FloorTileCounter++;
yield return new WaitForSeconds(tileDrawDelay);
}
}
}
Coroutines can only delay themselves. The code that called StartCoroutine will not be delayed
Having a yield as the final statement in a coroutine is therefore pointless
Sorry I still don't get it.
You said having yield as the final statement is pointless, but why does the Coroutine work in the second example but not in the first? They both have yield at the end
Can you explain what I did differently in the second example compared to the first that made the delay work?
In the second example the yield is not at the end of the code, it is embedded in a for loop
I presume you do know how a for loop works
Oh right. but even if I put the yield in the first example as the first statement, the delay still doesn't work. I don't understand how to fix this
because as @leaden ice said, Coroutines do not stop the calling process
the solution is simple really, whatever code you are running after the StartCoroutine, move it into the coroutine itself
When it hits the yield it will immediate run the rest of the code from where it was called (i'm assuming update?) without waiting. Only the rest of the COROUTINE will wait for the delay
Yield means it will yield the thread for other code to run. Just like a yield sign when driving, you stop and let the other car go, then you go
Okay, I think I need to do some refactoring then, because the code that runs after StartCoroutine goes back to a static method with parameters, which is calling PaintSingleBasicWall() in a for loop. And Coroutines don't work with static methods as far as I know
of course they do, there is nothing that special about a static method
hey guys. im trying to spawn a flare prefab when the player presses the m1 button. but im getting an error and the prefab is not spawning. do yall know whats happening?https://hatebin.com/pyjchojdue
hello, I have a SO Item. I have a simple class called ItemStack (not MB, not SO) that has an Item attribute and an amount attribute, and an Inventory SO, which has a List<ItemStack> items. how can I make it so that in the inspector of the inventory you can see both the amount and the linked Item SO? right now it only shows the reference to the ItemStack object, and not the amount and referenced SO.
the first image shows how it shows up, and the second shows how i want it to show up.
What is line 47.......
ok in SpawnProjectile there are three variables can be null
rb, projectilePrefab, playerCam, log them all
is ItemStack class set to Serializable ?
yeap:
ah wait, im stupid, oki trying now
oh wait
works now... im so stupid

thank you so much!
np!
cant believe i spent 2 hours on this
What do you mean by this? Coroutines don't work with static methods. StartCoroutine() can't be called inside them
startcoroutine is a method of monobehaviour....
so as long as you have a reference to monobehaviour you can call it
oh nevermind
of course it can
static void MyMethod(MyMonoScript script) {
script.StartCoroutine(...);
}
Sorry for the late reply
Yeah I guess that is the problem then, I am trying to make use of it for for following this "InputDirection
This is a float that should be controlled by the angle between character's Forward Axis and the Input Axis Vector. So for example, if the joystick is bent right, the angle will be 90 degrees, if back, the angle will be 180 degrees and so on."
I forgot this class doesn't inherit from monobehaviour
Any Mono class will do
Vector3.SignedAngle gives you an angle in the -180..180 range if that's what you need
You would use Vector3.up as the axis parameter since it looks like your movement is on XZ plane
Would anyone have any idea why my character is looking like this and snapping etc at all?
I've been having a lot of issues with this problem, even with different animation packs, so I have to have something wrong somewhere.
I decided to try using Kubold's Run Animset Basic which comes with a controller pre-setup specifically just to test if it was my animator states or not.
It currently looks like this
https://gyazo.com/ae0e40053dfebc2a5541315fb8aed7e4
In the animator preview, it looks perfectly fine
You can see the values input direction is receiving.
There's even a weird thing of the character 'inverting' where, if I do some quick direction changes,suddenly I press A and the character tries turning right etc
I'll paste my code below in the next message
Oh thanks for that. I actually had a separate project open which was a new one, the one you replied to was me trying a fresh slate specifically to try and fix this animation issue with root motion I have right now
I've actually been stuck on trying to get this root motion movement to work for about 2 weeks now and I still can't figure out where it's going wrong. Even though I now have just used a pre-built animator setup 😂
There's something really wrong with a setting or code or something
I'll show what the readme for the animator says which is
The graph is controlled by 3 variables:
-
InputMagnitude
This is a float that should be controlled by Input Axis Vector Magnitude (so for example, how far is the joystick bent). It controls the transitions between Idling and running. -
InputDirection
This is a float that should be controlled by the angle between character's Forward Axis and the Input Axis Vector. So for example, if the joystick is bent right, the angle will be 90 degrees, if back, the angle will be 180 degrees and so on. -
IsRightLegUp
This is a bool that should be controlled by which foot is currently higher in a run cycle, so the controller knows which animation it should play while stopping. Easiest way to get this info is checking which foot bone has a bigger Global Transform Y at the moment. So, if right foot is higher - we change IsRightLegUp to true.
So, if anyone can see where I'm going wrong, I would greatly love some help 😭
Big problem trying to fix animations in code (Root Motion)
if I want to load a scriptable object asset via its guid, do I need to use the addressables package? is there a simpler way?
edit: i see i can probably use asset bundles for this as well. (the resources approach seems to be not recommended)
so between addressables and asset bundles what is the correct choice here?
edit2: i see the addressables package is just a wrapper over asset bundles, so i assume the question is mute
You could also "index" them from a scene object.
could you elaborate a bit please? i am not sure how to do that or what to search for
You just put a script on an object inside a scene that contains your scriptableobject.
hello! I'm using VS code for programming in Unity and it keeps proposing me stuff from not implemented namespaces. On the picture it proposes to use methods from Unity.VisualScripting, but I'm not using this namespace. Do you know how to disable it and make it show code proposals only available from implemented namespaces?
ah, didnt think of that. i wonder why the unity sample game didnt do that. instead they load it async via adressables.
Can you serialize a subclass/implementaion of an interface?
I am working on a procedural generated map using top down 2d tiles and was wondering if there is a way to give certain Tile variables collision?
Because it is arguably better due to the finer control you have on the loading/unloading of asset.
Yes, SerializeReference
Thanks, I'll read up on it
Why is Sin of 180 saying its this
You have to click the left image
xVelocity = Mathf.Sin(180);
Debug.Log(xVelocity);
actually heres the code
it's in radians
oh shit thanks
So if you try to check anim.GetCurrentStateInfo(0).loop on a blend tree is it normal for it to always return false even if all of the states in that blend tree are set to loop?
What does sending a project do can it be bad
Might need more context to that question
Nvm lol
does anyone know why the onclick for button does not detect the function I have in the script?
Looks like you linked the script on your button click, instead of an object in the scene the script is attached to
i followed a tutorial on making a field of view raycast on a enemy. The tutorial was about a 3D project, and mine is 2D. I tried to "directly translate" the vector3 to vector2 but it didn't worked
hold up, i'll send it as a text
do you think i could share screen wtih you?
NavMeshAgent agent;
public float radius;
[Range(0,360)]
public float angle;
public LayerMask targetMask;
public LayerMask obstructionMask;
public bool canSeePlayer = false;
void Start()
{
agent = GetComponent<NavMeshAgent>();
agent.updateRotation = false;
agent.updateUpAxis = false;
playerRef = GameObject.FindGameObjectWithTag("Player");
StartCoroutine(FOVRoutine());
}
// Update is called once per frame
void Update()
{
if (canSeePlayer == true)
{
agent.SetDestination(playerRef.transform.position);
}
else
{
return;
}
}
IEnumerator FOVRoutine()
{
WaitForSeconds wait = new WaitForSeconds(0.2f);
while (true)
{
yield return wait;
FieldOfViewCheck();
}
}
void FieldOfViewCheck()
{
Collider[] rangeChecks = Physics.OverlapSphere(transform.position, radius, targetMask);
if(rangeChecks.Length != 0)
{
Transform target = rangeChecks[0].transform;
Vector2 directionToTarget = (target.position - transform.position).normalized;
if(Vector2.Angle(transform.position, directionToTarget) < angle / 2)
{
float distanceToTarget = Vector2.Distance(transform.position, target.position);
if(!Physics.Raycast(transform.position, directionToTarget, distanceToTarget, obstructionMask))
{
canSeePlayer = true;
}
else
{
canSeePlayer = false;
}
}
else
{
canSeePlayer = false;
}
}else if (canSeePlayer)
{
canSeePlayer = false;
}
}
}```
I think I attached the script to the model that the script intends to modified, but I'm not sure how to get the button associate with this script
So now, on your button, under "Runtime Only", you now want to drag your model to that slot, then you click where you currently have "MonoScript" it should show you all the components and scripts attached to that object - your "TigerShow" script should then show up in that list
Though you may want to make that model a prefab, it looks like that script is currently not saved as being a part of that object (indicated by the green "+"), and looks like the model file itself, usually youd make a prefab using the model
Im not sure about your specific issue, or what you mean by "didnt work", though it might help that Physics is a class for 3D casting, there is also Physics2D for 2D casting (though its used for more than just casting), you likely want to use that with your Vector2's, but with it, it may also have slightly different params/function names, so you can check the docs for similar functionality: https://docs.unity3d.com/ScriptReference/Physics2D.html
why isn't the texture showing?
Wrong shader for your render version
what should i change it too, sorry i'm new
Not a coding question but convert shaders to proper one. There’s an option in one of the edit drop downs. Idk what
OH sorry posted in the wrong channel
Any one is on unity pulse
this is a code channel
Yes
and your question is not code related
just cast it to byte with (byte)
A byte is 8 bits, not 4 btw
I want to avoid doing this, since I'll be doing this 2-3 times per 24 lines of code
that's unfortunate. the 0b prefix doesn't seem to work in .net framework 🤷♂️
I think I'll just have my constructor take in ints instead :(
It works, but automatically sets 32 bit precision
Even if your declared value doesn't require that much precision
i meant for a byte literal obviously
oh sorry
is there really gonna be a performance difference? are these lines of code running every single frame, 2-3 per frame is nothing
i think they meant they don't want to have to include the cast to byte so many times
I just wanted to avoid the clutter
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
okay so i was a bit wrong. after doing some more digging, i think what is actually happening is that your bytes are being widened to ints for the purpose of the addition so you'd end up needing to cast the entire result back to byte.
i believe this was changed in more recent versions of .net. I know in .net 7 byte implements the IAdditionOperators<byte,byte,byte> so i think that takes care of that issue, but i could be wrong about that
but i cannot find any operators on the byte struct in the source for .net framework so i cannot say for sure if this is actually what is happening.
Is there a way to show a public generic list in the inspector?
I made one in a ScriptableObject but it just won't show up
can you be a bit more specific about what you mean?
A list that can contain any type of object
That's what I suspected was happening, yeah. I'll never end up adding two numbers which result in a number > byte.MaxVal anyway tho so it's just an inconvienience for me. Issues now mostly solved tho. Thanks for the info
so rather than a generic list, do you mean a List<object>? because i don't think unity can serialize the object type like that.
if that is not what you mean, then provide actual details
Why would you want that? Seems like an XY problem
explain what you're doing with the list if you can, i doubt you need a list of just object
I'm trying to do that in a scriptable object
Because I have dialogues, which are a list of either strings or gameobject (characters expressions)
if you really need to use the byte type and you want to add bytes together frequently you could always cheese it with an extension method.
public static class ByteExtensions
{
public static byte Add(this byte a, byte b) => (byte)(a + b);
}
then you can just do someByte.Add(1); and it will return the result as a byte
Store them on a class and serialize the class or SO. Then store a list of those classes.
Use an enum to know which type it is
But can't a list only store one type of objects?
Yeah, like the single type of class or SO with all the data you need
[System.Serializable]
public class DialogueData
{
public DialogueType typeOfDialogue;
public string text;
public GameObject expression;
}
public List<DialogueData> data;
Basic example done on my phone
An SO would be better, but that's more writing for me
That’s a thing?
I might actually switch over to using that, probably should
yeah you can do a lot of handy stuff with extension methods. or you could just write your own static class with some static helper methods that do it too 🤷♂️
Yeah looks great, but then every dialogue element would have 3 types of data instead of 1, possibly making the inspector crowded. Maybe that can be fixed with a custom inspector?
You could also make two lists and just do one for dialogue and one for expressions.
Or a dictionary, but you'd have to make a solution for serializing it
Or yeah, custom inspector I guess
Thanks! That's a good direction
So I'm just using the camera look script that can be created by following countless tutorials, but whenever I do it, it looks far more choppy than it does in the tutorials. Here is a clip demonstrating what I mean. I'm moving my mouse at a (fairly) constant speed, but it doesn't appear that way, and it's quite distracting to play with. Is this a common bug, and if so, how do people usually fix it?
are you multiplying your mouse input by deltaTime?
yes
well there you go, that's the biggest reason why
no matter what though, the best way to solve this is to switch to cinemachine instead
Ok thanks. I've heard about cinemachine, but I've never used it before, so I guess it's time to look into that.
Oh wow, I don't know why I didn't know that. Thanks, that instantly cleared up that issue.
it's a very common issue perpetuated by some of the biggest youtubers that make unity tutorials. but it is wrong because the mouse input is already framerate independent
Yeah that makes sense. I'm surprised that those youtubers don't seem to be aware of it though.
How can I have a field that is a collection of type T, where T somehow refers to the class' **name ** (not instances) of extenders of some abstract class A?
Currently, I have an enum that provides a 1:1 mapping from enum to said A extendors. This works but I sense that it's an unnecessary step.
generic constraint?
Could you give me an example of how that would look on a field?(: (or property perhaps?)
not sure if this is what you want
you can just do where T : A, though idk what this has to do with your mapping in enums
Ahh yeah so I'm familiar with the generic contraint on method arguments, but what I'm after is something like...
public Type<T>[] Classes { get; set; } where T : typeof(AbstractClassName)
What I've posted there is invalid of course, but it's what I'm imagining I want
cant you just AbstractClassName[] classes.....?
I don't believe what I'm trying to do in the game impacts my desire. This is really a C# question haha
So I'm after that type of the class, or the "class name", not instances of the class
it does impact because what you are writing makes no sense. I am trying to see if there is a better way
You use an example with invalid syntax, then say it is invalid but its what you want. This is completely not understandable
Then don't respond(:
I cant imagine you'll get much help if no one knows what you want, but ok
public Type[] Classes { get; set; }
This is valid, and I could use this, but this doesn't restrict the Type's that can be provided - I think any class could be privided to this array
I want to add a restriction on the type such that it only accepts names of classes that extend some abstract class
It's just you buddy haha
you may have a look https://stackoverflow.com/questions/49967778/constraint-on-params-array-of-types
Wow amazing, thank you! That was my question exactly
Any idea how can I implement something like area pool? Basically I have a square of 10000 size. What I need is place some things on it of unknown size without overlaps and then remove them.
if you google "line rider in unity" you'll get many examples of how to get started with something like this
Does anyone have any idea for this at all?
https://discord.com/channels/489222168727519232/1172973780633665556
what would a pool achieve here? describe the problem in more detail
it's a space pool for scenes. Whenever there is a need place somebody into a scene - I need a free space for that scene where it will be spawned. So this "pool" is about tracking occupied space
here's picture that might illustrate it
where number is order of when spaces got allocated
i would say this is extremely difficult (or even no solution)
it looks like k-d tree some how
it's 2d fully
I know it's supposed to be complicated
but even a brute force idea will do for now
is the allocated space always rectangluar (or axis aligned)?
use k-d tree should work but the strategy of dividing space will affect every steps after it
k-d is 3d though
any 3d space partitioning can be "collapsed" to 2d by ignoring one axis
spatial hash can be used
strategy:
keep the leaf node==free space, when requesting for space iterate all leaf node, find a smallest node than can fit the need, generate two new leaf nodes
malloc algorithm but 2d version.....
though i havent written a malloc yet
k-d is dimension agnostic. That's what k-d means, k-dimensional, meaning any number of dimensions.
wait, how to free a requested space in kd tree approach......
maybe just use the free list, keeping a list of available AABB
request: find a "suitable" AABB, then subdivide it generates two new AABBs
release: iterate all AABB in free list, if the returned AABB can be merge to any AABB then merge it, and keep checking if the newly generate AABB can be merge
malloc again...
transform.localEulerAngles = Vector3.Lerp(transform.localEulerAngles, weaponRotTarget + weaponRotOffset, weaponRotSmoothRecoil * Time.deltaTime);
weaponRotOffset = Vector3.Lerp(weaponRotOffset, Vector3.zero, weaponRotReturnSpeed * Time.deltaTime);
This code is causing the object to glitch out as seen in the video.
how am i meant to send the video without it being a download
Not sure how to request free space this way.
I was thinking about tracking occupied AABBs
so then I could generate one big occupied AABB
do you know what is free list? i just steal the idea from malloc
and find space nearby
Nah, I don't
most of your thougts out load are gibberish to me 😅
someone tipped me about Rectangle Packing
suppose you have a 2d space
11111
11111
11111
now the free list is just one elements: a 3x5 area
you want to request a 2 by 2 area, then the "malloc" iterate the free list, find this 3x5 area, subdivide it to be
222 and 33333 (it can also be a 2x1 and 3x3 area depends on how you subdivide the space)
222
and returns
11
11 (in top left corner)
now the space becomes
AA222
AA222
33333
and there are two elements in the free list : 1x5 area (the 3) and 2x3 area (the 2)
so i say this is 2d malloc....
how do I figure how I subdivide?
also, should have mentioned. Space in the middle must be pre-allocated
basically it's more like
the "malloc" can handle this kind of allocation, but four AABBs will be generated
btw how to subdivide the AABB is quite important and i may try to maximize AABB area (one AABB is more "squarer")
now the problem is how to find out a continuous block when a long block is requested in my strategy, may be search for AABBs nearby and combine them, but costly operation

@vague slate How do you want to deal with cases when there's not enough space, due to how it's packed? You could pack it in an ideal way, but if you then remove random bounds out of it, you can end up with a less than ideal arrangement. You can't move bounds after they have been placed, right?
I want it to return false
I'm fine with being out of space
because it's not realistic in our real case scenario
and if we are - that means we are very rich and succesful 😅
but yeah, moving allocations is forbidden
I'm fine with bad packing
eventually all will be recycled
but I just need an algorythm that can keep going as those get allocated and deallocated
if moving allocation is allowed, it is a garbage collector....much harder than plain malloc
it's not
And no requirements for how the allocations should ideally be arranged? Your example showed them crowded towards the top left corner.
no strong requirments, more like a preference - start closer to middle
but we'll be totally fine without it
we are limited by float precision here. -9999 to 9999 is good enough
basically a square of 20k
this is our space
I think the first step in the algorithm when looking for space should be to go over the deallocated bounds. That's a simple binary search, just maintain a list of deallocated bounds, sorted by their size, and you can quickly find a deallocated zone that is just big enough.
Hmm, I suppose that's one way to deal with it. If you have one box in the middle, then you'd need to split the area around it into four initial deallocated bounds.
in the middle I'll have a bunch of pre allocated things, that will forever occupy spot somehwere in the middle
it's not exactly box, it' smore like many boxes
So your initial bounds could look something like this.
but to simplify I guess I could just round it to box
As for how to split a rectangle once you've selected one, you can do it like how k-d tree nodes are split. Split the rectangle along it's longer axis, just long enough to fit the long axis of the new rectangle. Then split the other axis. You end up with three new bounds, one of which becomes the new allocated rectangle. You remove the old large bounds from the sorted list and insert the two new ones.
But this doesn't scale super well. You'll end up cutting the space into a bunch of small pieces, and eventually, there won't be any bounds big enough for new, larger allocations. So you'll probably need some kind of clean-up routine that can merge nearby bounds into bigger ones.
original space is 20k and mostly allocations are going to be about 200x200 or less
Are the allocations always square?
I don't think it would help with this approach, but maybe there's a different approach that works better with squares. The box in the middle kind of messes that up though, I think.
Maybe there's some way to use a k-d tree for this, but it's structure is optimized for look ups of specific positions. I think a sorted list of bounds and a binary search will always be faster for what you need, which is to find the smallest zone that's big enough for a new zone.
yeah, that's something at least
Maybe you can keep track of the splits you make to make merging easier later. If you see that both nodes that were split are now empty, you can merge them again.
good enough for start
Hmm, actually, since it's rectangles, I guess you can't really keep a sorted list of them. X and Y would need to be separate. Squares would simplify that, but lead to less ideal packing. The initial bounds would then be (roughly):
Maybe there's a smarter way of doing a binary search of X and Y separately, I just can't think of one.
i would sort it based on width then height (or vice verse and perform upper and lower bound search for width then iterate in the bound (i think no need to do lower and upper bound search for height for different width, unlikely to have a bunch of AABBs that have same width)
maybe either lower or upper is enough
since you still have to iterate, just break
Oh yeah, right, that makes sense. Good idea.
same aabbs are more than likely
If it's sorted by width and then height, and you're performing the binary search with the same comparison, then you shouldn't need a lower and upper bound search, right?
Many scenes will be loaded multiple times for it
This assumes the rectangles can't be reoriented for ideal packing, though.
they can't be
you are trying to find out the smallest AABB>=requesting AABB (ie width and height>= the AABB's width and height)
maintaining a ordered list may not be useful since you still have to iterate the list while the sorting can only sort it based on one key.....
I mean just 90°, so it would still be axis aligned.
I get it, but I'm not sure if this can be supported
potentially it can
we move scenes anyway
just not as of now
@swift falcon can you help me
i'm having a problem with the 2D navmesh system. it was working fine until i deactivated the navmesh game object to edit some props in the scene. when i finished, i casually turned it back on and tried to bake it. the blue mesh that shows the walkable surfaces did not appeared. i tried to run the game and the enemy wasn't walking. I saw that the CollectorResources2d was off, and i couldn't turn it back on. When i tried to add it again this error mensage showed up
i tried to restart unity
the file name and the class name are the same
tried to reinstall
but it just doesnt work
Can you show a screenshot in your IDE showing that the class name and file name are the same?
Hmm, it doesn't derive from monobehavior though. Not sure if this is allowed.
u have any idea of how can i fix this
what really upsets me is that it was working fine until i turned the gameObject off
No not really, I'm scanning the docs but this addon seems ancient.
But I don't see anywhere why you would need to add this script on an object.
i saw this tutorial https://www.youtube.com/watch?v=HRX0pUSucW4&t=89s. and when he says that i need to create the navmesh object, add the navmesh surface component, he will simply add the CollectSources2D component
GitHub project for 2D Navmesh pathfinding:
https://github.com/h8man/NavMeshPlus
Join the discord server: https://discord.gg/q8yAPqEG
the component showed up to me before
but now it doesn't
Well, that's NavigationCollectSources2d, that seems like a different script.
yeah, but it's the one i found and it worked at the same way
this video is some months old
so it could be just an small update
Okay, can you show me this then in your project?
show what exactly?
Well you say your following this tutorial, then you need to have a NavMesh gameobject with a NavigationSurface, where you can add this Extension onto.
So show me your NavMesh gameobject with a NavigationSurface, and you trying to add this script.
Can you show a screenshot of your Console then? Did it even compile?
If anyone is familiar with the Odin Inspector, is it possible to create a drawer/custom inspector to display an haxgonal grid ? The TwoDimenstionalArray class only allows for grids, and offsetting the rows seems to mess with the graphics
This seems corrupt to me, you don't have your script name there in your component and your missing everything that the tutorial guy has.
Anyhow, seems super messy, I don't know how to fix all this.
thanks for trying man, appreciate it
I'm trying to procedurally generate a mesh for a 16x16x16 chunk of voxels, but I'm getting this odd error where the algorithm messes up on block 11, 11, 11, and the rest of the vertices positions begin to collide with existing vertices in odd ways
ChunkMeshGenerator Script: https://pastebin.com/ehYcAQGd
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.
Drawing a single block at 11, 11, 11 works fine, drawing a single block at 12, 12, 12 works fine
I seem to be hitting some sort of cap
The position of a vertex along one axis relative to the chunk is defined by 6 bits, so I hit an understandable limit when trying to generate vertices of blocks beyond 63, 63, 63
Yup, i figured it out
I actually was hitting the max vertex count per mesh
changing mesh.indexFormat to 32bit gave me more than enough space
I initally suspected this was happening but when I searched up default max mesh vertex count and saw it was 65k i was like 'yeah no chance im hitting that'
My unculled 16x16x16 mesh takes around 100k verts
Good time of day, guys!
Somebody know how to make IPointerClickHandler to propagate the click message to it's parents?
Structure is like:
Root
- "Toggle" component (is interactable ON)
--- Graphic (raycast target) and another IPointerClickHandler script to invoke some analytics.
So as soon as I'm adding the IPointerClickHandler, Toggle stops to react on clicks.
Straight idea is to find any click handler in parents and call it's OnPointerClick with the same input parameters, but I'm not sure I like it. Or that's how it works?
Im so confused. I have a prefab with a script on it. The variables on the script are saved after the runtime is stopped. For on the prefab i have skinnedmeshrenderers to add clothes. Even the clothes are saved into the prefab
then you are updating the prefab in code instead of updating the Instantiated object created from the prefab
yup
holy shit
whole block is pObject (instantiated object) and then that script is somewhy being accessed by playerPrefab
im just blind 🙂 thanks
any way to see why unity freezes? It's like the fifth time today, and i cant find what i did wrong. In middle of the game it just freezes and i had to bring up task manager to stop it
any while loops in your code?
i feel like it is related to this, once i start it, it should change the text to 5, but that doesnt happen
IEnumerator StartCountDown()
{
int count = 7;
while (true) {
yield return new WaitForSecondsRealtime(1f);
count--;
MultiplayerManager.RelayMessage(null, count.ToString(), "CountDown");
if(count == 0) {
GameController.OnGameStarted(true);
GameRunning = true;
StartCoroutine(sendPooledPosition());
countText.gameObject.SetActive(false);
PlayerBehaviour.instance.StartMpUpdate();
break;
}
}
}```
nvm i think i found it
are Debug.Logs done synchroniously?
Yeah
then wtf 😄
{
int count = 7;
while (true) {
yield return new WaitForSecondsRealtime(1f);
count--;
countText.text = count.ToString();
Debug.Log("reacheaaad");
if (count == 0) {
Debug.Log("bbbb");
GameController.OnGameStarted(true);
Debug.Log("cccc");
GameRunning = true;
Debug.Log("kkkk");
StartCoroutine(sendPooledPosition());
countText.gameObject.SetActive(false);
PlayerBehaviour.instance.StartMpUpdate();
Debug.Log("999");
break;
}
MultiplayerManager.RelayMessage(null, count.ToString(), "CountDown");
}
}``` it counts down to 1
and crashes
it wont trigger the count == 0, since it crashes at 0
The other party does receive "1", but not 0
try commenthing out everything inside the if statement except one Debug.Log()
i mean, it isnt reached
i think the problem is not here, but not much is happening in background except this
it basically crashes somoewhere here where count is 1 or 0
yield return new WaitForSecondsRealtime(1f);
count--;
countText.text = count.ToString();
You should make your debugs better by passing values in (like count, so you can verify exactly when it crashes)
Can you show the sendPooledPosition coroutine?
IEnumerator sendPooledPosition()
{
PooledPositionData pooledData = new PooledPositionData();
while (true) {
if (!GameRunning)
yield break;
if (!changedPool)
continue;
Debug.Log("addingToPool");
yield return new WaitForSeconds(0.04f);
pooledData.data.Clear();
foreach(LobbyPlayer player in lobbyPlayers) {
pooledData.data.Add(player.positionUpdateData);
}
MultiplayerManager.RelayMessage(null, JsonUtility.ToJson(pooledData), "UpdatePosition");
}
}```
yeah, ill try placing better debugs
this would run while true without waiting if changedPool is false, ill fix that
but it isnt reached, so dont think it matters
lol wtf now it works
maybe it was that yield waitForSeconds was after if(!changedPool) continue;
Oh yeah, that would make sense. It will take the main thread over until changedPool is false
And that would be in line with it happening when count is 0
Maybe throw a yield return null before that check
i just moved the yield return to top
I installed the addressables package, but I cant do "using UnityEngine.AddressableAssets;" because the AddressableAssets can't be found. any ideas why? I can see the package being installed in the packages folder. i have 30 other packages installed, never had this problem.
Regenerate project files
Probably just the ide being out of sync
thanks, that was it!
Hello, what's the best way to use Vector2, but with strings?
Just like this (string x, string y) ?
assuming that I don't have time and wish to create a struct
Oh, well, I see, I do have a wish to create a struct now
and time
I don't know why you're invoking the name Vector2 here but you seem to be asking about tuples?
Vector2 is a run of the mill struct
Yes, I was talking about tuples, but I've decided to use a struct already 😅
[Serializable]
public struct Vector2String
{
public string x;
public string y;
public Vector2String(string x, string y)
{
this.x = x;
this.y = y;
}
}
apparently, wasn't that hard to create
they are not hard to create, no
yeah, I've noticed that..
thank you for the tip 😄
Consider overriding Equals and GetHashCode if you're going to do equality checks on them, and storing them into collections
structs are nicer anyway because accessing stuff item1, item2, ect is uggggly
You can name them so you access them with variable names
oh really ok I take that back then
I still prefer structs though haha
Need help with some algorithm right now, my brain is fried after a whole day of programming, I want any extra bullet the player shoots to go like this:
https://img.sidia.net/ZEyI5/BUMuPeKe86.png/raw where 0 is straight forward, the next bullet gets added x degree to the left, next one same amount on the right, next one x*2 degree to the left, then again same amount on the right
What I do right now is spawning them random between a certain - and + degree, but that looks very concentrated to the center
for (var i = 0; i < bulletAmount; i++)
{
var bulletEntity = _contexts.game.CreateEntity();
var randomRotation = (Random.value - 0.5f) * i * 10;
// var sign = i % 2 == 0 ? -1 : 1;
var rotation = Quaternion.Euler(0, playerEntity.rotation.Value + randomRotation, 0);
bulletEntity.AddBulletDirection(rotation);
}
Getting what side to spawn the bullet on through % is easy, but i cant really figure out how to raise the amount of degrees only every 2nd value of i
the fact that only one (and not two) bullets goes exactly straight forward makes it a little more annoying to set up