#archived-code-general

1 messages · Page 220 of 1

quaint crypt
#

oh, i did not know that, thanks!

loud wharf
#

System.Numerics.Vector3 might suffice? UnityChanThink

rigid island
loud wharf
#

I thought the implicit cast could exist anywhere.

rigid island
#

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'

craggy totem
#

Hello can i predict if car will hit other car or won't hit?

leaden ice
craggy totem
west sparrow
#

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.

lean sail
craggy totem
leaden ice
cold willow
#

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

leaden ice
cold willow
#

Ahhhh, that makes a lot more sense. Thanks.

tawny mountain
#

Is there a way to use vector images in unity

craggy totem
#

@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

leaden ice
#

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.

dusky lake
#

So you want the Dictionary to contain inherited classes of Component?

#

Or why the hassle with the dynamic type

leaden ice
#

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

dusky lake
leaden ice
#

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

dusky lake
#

Compiler doesnt complain, didnt test runtime though

leaden ice
#

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

dusky lake
#

Yeah that could work

spare island
#

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?

dusky lake
#

If you dont care about order you can get all of them via reflection and add them to the list

spare island
#

well I do need the steps to be in order

dusky lake
#

Then manually adding them is your way to go i guess

spring creek
rigid island
spare island
rigid island
spare island
#

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

rigid island
#

just do it in the inspector

spare island
#

think i'd have to make em serialized then

rigid island
#

yeah or use SO

spare island
#

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

rigid island
#

SO will just be a POCO as an asset pretty much.

spare island
#

what is a POCO?

rigid island
#

Plain Old C# Object

#

like a class

#

if Monobehavior + c# object and asset made a baby you get Scriptable Object xD

dire marlin
#

hey guys is there a way to bake occlusion culling during playmode

strong escarp
#
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

west lotus
#

Debug.Log the collider that is triggering the trigger.

strong escarp
#

what do i remove?

spring creek
#

Right now it could trigger on the ground

#

Or anything

strong escarp
#

but its not touching anything i made sure of it

#

its hovering

spring creek
strong escarp
#

oh??

spring creek
#

But what do you WANT it to trigger on?

strong escarp
#

player

#

its supposed to trigger a scary sound

spring creek
#

Could do something liker:
if (other.CompareTag("Player"))

strong escarp
#

where do i put that

#

before play?

spring creek
#

Play would be inside that condition

#

if (condition)
{
//do stuff
}

strong escarp
#

oh

#

yeah

#

cant wait until scripting isnt confusing for me

strong escarp
#

those

#

do

#

when like
{

}

spring creek
strong escarp
#

yeah

#

it giv error?

#

is this incorrect?

strong escarp
#

if i miss one letter nothing is working💀

spring creek
strong escarp
#

i forgot to delete

spring creek
#

Also, your !IDE is not configured it looks like

tawny elkBOT
strong escarp
#

it didnt work before

spring creek
#

Oh also, you need the curly braces {} for the OnTriggerEnter method

void OnTriggerEnter(Collider other)
{
if (condition)
{
//stuff
}
}

rigid island
strong escarp
#

lol

rigid island
#

theme is wild

spring creek
strong escarp
#

i am

#

wait

#

why cant i say

spring creek
#

Honestly, it should have blocked ye and wait too

#

Hahahaha

cosmic rain
#

Try typing more than 1 word in your messages.

strong escarp
#

one

strong escarp
cosmic rain
#

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.

strong escarp
#

idk

rigid island
#

regex having a hard time rn

strong escarp
#

waht?

rigid island
#

nuthin

#

the bot uses regex

cosmic rain
#

Point is: stop spamming and get to the point. Preferably in one message.

strong escarp
#

ohhhh yeah

rigid island
#

fix what?

strong escarp
#

my problem is it plays as soon as game starts

#

soun

spring creek
#

Show the current code, not og

strong escarp
#

well idk how to make those changes cause i know NOTHING about c#

cosmic rain
#

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.

spring creek
cosmic rain
#

Also, config your ide before continuing.
!ide

tawny elkBOT
spring creek
strong escarp
leaden ice
#

Configure IDE first

#

Before anything

strong escarp
#

i dont know what ide is?

leaden ice
#

Vscode is the ide

#

Configure vscode

#

Or visual studio

#

Whichever you're using

cosmic rain
#

You've been linked the bot message regarding it several times too.

tawny elkBOT
cosmic rain
#

You don't need to repeat that...

strong escarp
#

mhm

ashen yoke
#

is there a trick to handling duplicate types in different internal unity assemblies?

#

i.e. prioritize CoreModule ones, or something similar

thick terrace
ashen yoke
#

collisions in a dictionary

#

currently opting for assembly name + full name

frozen compass
# ashen yoke currently opting for assembly name + full name

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 😄

knotty sun
ashen yoke
#

if you know why its bad please share, I want to know

ashen yoke
#

unity has a lot of duplicate namespaces and types in various assemblies

knotty sun
ashen yoke
#

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

knotty sun
#

It is, in fact, obsolete, are you checking the custom attributes?

ashen yoke
#

obsoletion of this particular type doesnt mean others are

#

checking for it would mean the empty stub would be selected

knotty sun
#

no but it may cut down on your conflicts

frozen compass
#

im caching everything tools use once and

ashen yoke
#

thats a local remedy for one particular issue with unthought ahead consequences

swift falcon
#

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.

latent latch
#

Parent them and move the parent ;p

regal epoch
#

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?

heady iris
#

a "TextFieldInput" ?

regal epoch
#

Yes sorry that one

heady iris
#

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"?

regal epoch
#

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

heady iris
#

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

regal epoch
#

Ah I get it. Thanks

abstract parrot
#

InputField.SetTextWithoutNotify(NameFromPlayerPrefs);

heady iris
#

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

abstract parrot
#

yeah, usually better to use that instead just set the text in script

heady iris
#

both will work better than trying to set the text component's contents, of course 😉

fiery path
#

Are properties such as particle systems defined within an overall state machine or in the specific sub state scripts

fiery path
leaden ice
#

Also if you find yourself with numbered variables you almost definitely want an array instead

scarlet viper
#

can u prevent a variable from having its content copied when u Instantiate(<ExistingObject>) (cloning)

alpine turret
steady moat
fervent furnace
#

keep the data non serialized should work

fervent forum
#

hey guys ive been working with unitys XR toolkit and was wondering how to make something like this

fervent forum
#

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

rigid island
#

[SerializeField] private UnityEvent _myCoolEvent

#

using UnityEngine.Events

fervent forum
#

omg thanks, just one last question... how would i trigger a function from that😅

#

nvm figured it out... its invoke

#

but thanks😁

rigid island
lean sail
#

Do you need the null check on unity events? Not on pc but I vaguely recalling that you dont

rigid island
#

its always good to check if has no listeners although I think unity does something diff with UnityEvent instead of regular C# event

hybrid turtle
#

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

rigid island
#

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

knotty sun
normal jay
#

What's the best way to go about having a character walk up or down some stairs?

rigid island
normal jay
# rigid island 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

rigid island
somber nacelle
#

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

polar marten
somber nacelle
#

still gotta project its velocity on the ground plane when using KCC, but it's an incredibly well made character controller

short wing
#

[Help] I'm trying to implement a Civ5 hex terrain

somber tapir
#

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

normal jay
#

Thank you @rigid island @somber nacelle @polar marten

vagrant drum
#

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

vagrant drum
vagrant drum
rigid island
#

make the rocket Kinematic or freeze Rotation

vagrant drum
bleak thorn
rigid island
#

I said rotation

bleak thorn
#

rotation also

rigid island
#

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

bleak thorn
rigid island
#

probably because you use valocity/addforce

#

you need movepoistion

bleak thorn
#

yeah

#

is there other option?

rigid island
#

whats wrong with that solution?

regal marsh
#

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

rigid island
#

rocketRb.MovePosition( transform.up * speed)

regal marsh
#

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?

rigid island
#

I think MovePosition uses world pos

#

its been a while

#

lete me see

#

try rb.MovePosition(rb.position + ( transform.up * speed) );

quaint crypt
#

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

oblique spoke
brittle oyster
#

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?

polar marten
sinful robin
#

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

brittle oyster
#

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

short wing
#

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.

deep cobalt
#

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?

short wing
#

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

deep cobalt
#

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

short wing
#

Yep, they are transforming twice, you need two. Make a function to notify when changed, set also OnValidate to call that function

deep cobalt
#

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

short wing
#

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

deep cobalt
#

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

short wing
#

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

deep cobalt
#

right, I guess i'll only check for transform changes if the object is selected

#

thanks a lot, great help 👍

wise hollow
#
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;

hard viper
#

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

rigid island
somber nacelle
#

pretty sure Contacts are not updated until the physics is simulated

hard viper
#

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)

visual flare
#

which version of Unity added delta compile in IL2CPP? 2020 seems to recompile entire project even on scene change.

hard viper
#

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.

hard viper
#

I want to avoid casting the whole shape 4 times: up/down/left/right to check for directionality

untold siren
#

howdy, does anyone happen to have any good documentation about setting up a finite state machine for movement / character controler?

hard viper
#

i just use an enum tbh

rigid island
#

pretty much this ^

hard viper
#

and make some values in the enum that combine others

rigid island
#

I was looking at GTA III source code translated to C++

Surprising the amount of enums they used back then

hard viper
#

like:

Neutral = 0,
Jumping = 1,
WallJumping = 2,
MidJump = Jumping | WallJumping
}```
rigid island
hard viper
#

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?

cold willow
#

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

hot jolt
#

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

lofty compass
#

Any idea what the deal is here?

cold willow
sharp lotus
#

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

cold willow
lofty compass
sharp lotus
cold willow
lofty compass
#

Like Im following a tutorial and if we switch that isnt everything going to be confusing

cold willow
lean sail
sharp lotus
#

thanks for the help

cold willow
#

Happens to the best of us, I was just about to recommend that to you but glad you figured it out!

sharp lotus
#

yeah when you mentioned windows being closed but not actually closed it kinda clicked lol

lofty compass
#

This was the issue

#

I was confused when I tried some other ones, deleted it and fixed it

lofty compass
#

Thank you

lean sail
#

thats typically what that error will come down to

lofty compass
#

Rad, well yall are in here, any tips on what to add to a Targeting Camera so it doesnt disappear behind walls XD

loud wharf
lofty compass
#

Like I used a collider on my other one

somber nacelle
lofty compass
#

oooh neat

rain minnow
cold willow
#

Its the using statement that contains the LookRotation statement.

somber nacelle
#

no it isn't

#

LookRotation is a method on the Quaternion struct which-of course-is in the UnityEngine namespace

cold willow
#

Could have sworn it was in the collections, but now that I think about it that makes a lot more sense.

rain minnow
loud wharf
#

The Quaternion he's using is probably from System.Numerics.

somber nacelle
#

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?

loud wharf
#

Yeah.

#

Yeah probably should have read more.

broken heron
#

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?

steady moat
cosmic rain
broken heron
steady moat
broken heron
#

That going to explain why It's not continuing?

steady moat
broken heron
#

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.

cosmic rain
steady moat
#

You would just have to say: Hey, you, NPC 23, can you turn towards that ?

cosmic rain
#

That or have a loop inside the coroutine.

broken heron
#

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?

steady moat
broken heron
#

ok, ill rewatch the video. ty

steady moat
broken heron
#

ty!

loud wharf
#

Method that returns IEnumerator. It's completely fine to use it instead of IEnumerable?

spring creek
loud wharf
forest linden
#
            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

dusk apex
forest linden
#

size of zero

dusk apex
#

In the above, you've logged the size of itm.items

forest linden
#

and it returns the correct size

dusk apex
#

Is that the collection that you're looking at?

forest linden
#

yes

dusk apex
#

Can you verify this with an image?

forest linden
#
{"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

dusk apex
#

Is this the only child with the item component?

forest linden
#

no there is many

#

none of the other items have anything in the inspector either

dusk apex
#

Log other important stuff as well like the name of the object with the list

forest linden
#

I did that and it was correct

dusk apex
#

Or the name of each item being added

#

I'm unable to verify. If the logs are correct, the collections should be correct.

forest linden
#

at the moment the item ids being added are -1 as I want it to be empty

dusk apex
#

This line looks weird btw itm.items.Add(itm). Referencing itself

forest linden
#

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

forest linden
#
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

dusk apex
forest linden
#

how would itm.items.count return 1

dusk apex
#

If there were one element

forest linden
#

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)

dusk apex
#

If it's empty or one, that would be all that you would get

forest linden
#
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);
                }
dusk apex
#

Why not just print the size?

#

Your itm.items should theoretically yield the same result unless overwritten elsewhere

forest linden
#
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);
                }
dusk apex
#

So one itemIDs thus why you got one item

forest linden
dusk apex
#

Maybe you're looking at the wrong object..

#

Use the second parameter of debug log

forest linden
#

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

dusk apex
#
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.

forest linden
#

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'

tawny mountain
#

Does anyone know why objects have the blue navmesh walking path on the tops of them?

tawny mountain
#

and mesh filter

#

It's just basic cubes streched and moved

rigid island
#

you have to exclude those from the bake

#

use NavMeshModifier

tawny mountain
knotty sun
umbral agate
#

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

river zenith
#

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.

pastel apex
#

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?

pastel apex
#

nvm

ruby valve
#

hi

normal arch
#
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

dusky lake
normal arch
#

there could be loads of levels i feel like it would clog the matrix

dusky lake
#

are you loading all levels at the same time or just 2-3?

normal arch
#

all at the same time

dusky lake
#

Can you talk about what you want to achieve with this?

#

maybe there is a different approach

normal arch
#

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

latent latch
#

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.

dusky lake
normal arch
dusky lake
#

I dont understand why thats a problem

normal arch
#

because the multiple colliders would be at different height levels so i couldnt just base it all around one collider

dusky lake
#

then enable all colliders on which level the player has a collider

normal arch
#

no because then all the collider will intearct with all the layers

#

which are active

plain vine
#

Is it possible to intergrate a unity game into reactnative?

normal arch
#

it would be easier to use one manager script is what im saying

dusky lake
plain vine
#

what about ios?

knotty sun
# normal arch ```cs public List<List<Collider2D>> levels = new List<List<Collider2D>>(); publi...
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);
                   }
                }
             }
         }
     }
normal arch
#

yeah that works ty a lot

hard viper
#

is there a way to make the contents of a collection accessible as read only to other classes?

vagrant blade
#

Make it a property with a private setter

hard viper
#

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

fervent furnace
#

IReadOnlyXXXX interface

hard viper
#

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

gray mural
#

Hello, does [field: SerializeField] change any behaviour of the simple public title (non property) ?

[field: SerializeField] public string title { get; set; }
hard viper
#

yes

gray mural
hard viper
#

title is a property. you can't serialize a property

gray mural
hard viper
#

no you cannot

gray mural
#

using the method I showed above, you can

hard viper
#

you cannot serialize a property

#

title is a propery with an auto-generated backing field

gray mural
hard viper
#

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

gray mural
hard viper
#

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

gray mural
#

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?

hard viper
#

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

gray mural
hard viper
#

uhhh almost

#

fyi,. you can do something like this:
[field: SerializeField] public string title {get; private set;} = "Untitled"

gray mural
#

why would I?

hard viper
#

[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;}; }```
gray mural
hard viper
#

this is a very common and useful pattern

gray mural
#

that's what I meant

gray mural
#

anyway, using field: you can change neither get nor set

hard viper
#

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

latent latch
#

you can do private set

gray mural
hard viper
#

[field: SerializeField] public string title {get; private set;} = "Untitled";
This is a very common pattern you should memorize.

gray mural
#

thank you for your explanations 😄

hard viper
#

if you make your own custom get/set with actual logic, then you want to define your own backing field

latent latch
#

I use the backing field serialization everywhere but someone was saying if you want to rename the variables it kinda breaks the serialization

gray mural
latent latch
#

rather, gotta point to the location of the field and it's a pain

gray mural
#

annying with just one too though

hard viper
#

eg

public string title { get {return m_title;};
          private set { Debug.Log("New title = " + value); m_title = value;}; }```
gray mural
hard viper
#

well, yeah. you changed it lmao

latent latch
#

so in a sense it is better to just seperate the field if possible if you don't mind the clutter

hard viper
#

could someone explain the internal keyword to me? I'm confused as to when an assembly starts and ends

west lotus
#

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
latent latch
fervent furnace
#

&& dot<0

hard viper
#

I don't understand

#

wouldn't that be anything in my project?

rigid island
#

the DLL is the whole assembly

west lotus
hard viper
#

I have not been making any assemblies actively

mellow sigil
hard viper
#

I see. so it takes more effort to really define an assembly to properly use the internal keyword

rigid island
#

encapsulation basically

west lotus
rigid island
#

all it comes down to

rigid island
mellow sigil
west lotus
mellow sigil
#

What do you want to happen if one is true and the other is false?

west lotus
#

nothing

dusk apex
#

== ?

fervent furnace
#

you need else if

mellow sigil
#
else if(distance <= d.shadowFadeDistance && dot >= 0)
west lotus
#

thank you guys

hard viper
#

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.

loud wharf
#

Just the entire scope of the [C#] icon in the solution explorer is the entire assembly.

hard viper
#

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?

latent latch
#

What exactly is wrong with GetContacts?

hard viper
#

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

latent latch
#

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.

hard viper
#

closest point outputs a unique point

#

I need output as a set of points

latent latch
#

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

hard viper
#

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.

latent latch
#

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.

hard viper
#

also, I realize for casting a BoxCollider2D, it's very similar in cost to a single 2D raycast of same distance

latent latch
#

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.

hard viper
#

I see

latent latch
#

and that a cylinder collider is like 20x the cost of a capsule collider

#

¯_(ツ)_/¯

hard viper
#

well, I still have the challenge of discriminating these two

#

and knowing I have those two normals.

latent latch
#

If it's two different colliders (the blue walls) you get the closest point and you can get the normal from those

hard viper
#

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

hexed pecan
#

A cylinder will be expensive yeah, because it has to be a mesh collider since it doesn't exist as a primitive

latent latch
#

Ah, makes sense

thick parcel
#

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)

leaden ice
#
  • 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

gray mural
#

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

latent latch
#

that you're serializing the backing fields?

leaden ice
#

when you use an auto property the fields are named like that internally

gray mural
leaden ice
#

depending on which serializer you use, you can change it with annotations typically

leaden ice
gray mural
leaden ice
leaden ice
#

notice you have [field: SerializeField] on the other properties?

#

You would have to add that to these to serialize them too

gray mural
leaden ice
gray mural
#

but what do I do if I want to make them invisible in the Inspector, but visible in the json file?

leaden ice
#

[HideInInspector]

#

(and also serializefield)

gray mural
leaden ice
#

yes

gray mural
#

I see, I'll try it

#

It works now, thank you 😄

wise pumice
#

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);
leaden ice
#

You mean this?

float angle = Vector3.Angle(Vector3.forward, movementDirection);1```
#

Vector3.Angle only returns positive numbers

crude cairn
#

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);
            }
        }
    }
leaden ice
#

Having a yield as the final statement in a coroutine is therefore pointless

crude cairn
knotty sun
#

I presume you do know how a for loop works

crude cairn
knotty sun
#

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

spring creek
crude cairn
#

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

knotty sun
#

of course they do, there is nothing that special about a static method

next salmon
#

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

quaint crypt
#

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.

fervent furnace
#

What is line 47.......

#

ok in SpawnProjectile there are three variables can be null
rb, projectilePrefab, playerCam, log them all

rigid island
quaint crypt
rigid island
#

ohhh its a mono

#

thats why

quaint crypt
#

sorry i tried as a SO as well

#

same thing

rigid island
#

its a unity Object

#

make it a regular class

#

try it or struct

quaint crypt
#

ah wait, im stupid, oki trying now

rigid island
#

oh wait

quaint crypt
rigid island
#

ah ok

#

those properties dont show in inspector btw

quaint crypt
#

i forgot i made ItemStack a MB

#

deleted the getter / setter

#

and it does now

rigid island
quaint crypt
#

thank you so much!

rigid island
#

np!

quaint crypt
#

cant believe i spent 2 hours on this

crude cairn
fervent furnace
#

startcoroutine is a method of monobehaviour....

#

so as long as you have a reference to monobehaviour you can call it

crude cairn
#

oh nevermind

knotty sun
wise pumice
crude cairn
#

I forgot this class doesn't inherit from monobehaviour

knotty sun
#

Any Mono class will do

hexed pecan
#

You would use Vector3.up as the axis parameter since it looks like your movement is on XZ plane

wise pumice
#

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

wise pumice
#

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:

  1. 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.

  2. 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.

  3. 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)

quaint crypt
#

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

steady moat
quaint crypt
steady moat
misty blade
#

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?

quaint crypt
fickle sable
#

Can you serialize a subclass/implementaion of an interface?

silk edge
#

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?

steady moat
steady moat
fickle sable
#

Thanks, I'll read up on it

delicate ibex
#

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

somber nacelle
#

it's in radians

delicate ibex
#

oh shit thanks

chrome trail
#

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?

karmic pilot
#

What does sending a project do can it be bad

soft shard
karmic pilot
#

Nvm lol

jolly viper
#

does anyone know why the onclick for button does not detect the function I have in the script?

soft shard
vagrant drum
#

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

jolly viper
vagrant drum
#
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;
        }   
    }
}```
jolly viper
soft shard
#

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

soft shard
# vagrant drum ``` [SerializeField] GameObject playerRef; NavMeshAgent agent; public...

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

jolly viper
#

why isn't the texture showing?

midnight bane
#

Wrong shader for your render version

jolly viper
#

what should i change it too, sorry i'm new

midnight bane
#

Not a coding question but convert shaders to proper one. There’s an option in one of the edit drop downs. Idk what

jolly viper
#

OH sorry posted in the wrong channel

grim mesa
#

Any one is on unity pulse

somber nacelle
#

this is a code channel

grim mesa
somber nacelle
#

and your question is not code related

brittle oyster
#

How can I write a byte literal?

#

0b0001 doesn't work

somber nacelle
#

just cast it to byte with (byte)

spring creek
brittle oyster
somber nacelle
#

that's unfortunate. the 0b prefix doesn't seem to work in .net framework 🤷‍♂️

brittle oyster
#

I think I'll just have my constructor take in ints instead :(

brittle oyster
#

Even if your declared value doesn't require that much precision

somber nacelle
#

i meant for a byte literal obviously

brittle oyster
#

oh sorry

lean sail
somber nacelle
#

i think they meant they don't want to have to include the cast to byte so many times

brittle oyster
#

I just wanted to avoid the clutter

steep pewter
#

!code

tawny elkBOT
somber nacelle
# brittle oyster I just wanted to avoid the clutter

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.

swift falcon
#

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

somber nacelle
swift falcon
brittle oyster
somber nacelle
spring creek
lean sail
swift falcon
#

I'm trying to do that in a scriptable object

somber nacelle
#

why

swift falcon
#

Because I have dialogues, which are a list of either strings or gameobject (characters expressions)

somber nacelle
spring creek
swift falcon
spring creek
# swift falcon 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

brittle oyster
somber nacelle
#

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 🤷‍♂️

swift falcon
spring creek
swift falcon
inner yarrow
#

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?

somber nacelle
#

are you multiplying your mouse input by deltaTime?

inner yarrow
#

yes

somber nacelle
#

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

inner yarrow
#

Ok thanks. I've heard about cinemachine, but I've never used it before, so I guess it's time to look into that.

inner yarrow
somber nacelle
#

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

inner yarrow
#

Yeah that makes sense. I'm surprised that those youtubers don't seem to be aware of it though.

vague tundra
#

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.

fervent furnace
#

generic constraint?

vague tundra
#

Could you give me an example of how that would look on a field?(: (or property perhaps?)

fervent furnace
#

not sure if this is what you want

lean sail
vague tundra
#

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)

lean sail
#

Type<T>?

#

what are you trying to do in terms of your game

vague tundra
#

What I've posted there is invalid of course, but it's what I'm imagining I want

fervent furnace
#

cant you just AbstractClassName[] classes.....?

vague tundra
vague tundra
lean sail
#

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

vague tundra
#

Then don't respond(:

lean sail
#

I cant imagine you'll get much help if no one knows what you want, but ok

vague tundra
#

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

vague tundra
fervent furnace
vague tundra
vague slate
#

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.

delicate flax
#

if you google "line rider in unity" you'll get many examples of how to get started with something like this

wise pumice
ashen yoke
vague slate
#

here's picture that might illustrate it

#

where number is order of when spaces got allocated

fervent furnace
#

i would say this is extremely difficult (or even no solution)
it looks like k-d tree some how

vague slate
#

it's 2d fully

#

I know it's supposed to be complicated

#

but even a brute force idea will do for now

fervent furnace
#

is the allocated space always rectangluar (or axis aligned)?

vague slate
#

yes

#

we just use 2d aabb of scene

#

no need for bigger precision

fervent furnace
#

use k-d tree should work but the strategy of dividing space will affect every steps after it

vague slate
#

k-d is 3d though

fervent furnace
#

any 3d space partitioning can be "collapsed" to 2d by ignoring one axis

ashen yoke
#

spatial hash can be used

fervent furnace
#

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

late lion
fervent furnace
#

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...

forest linden
#
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

vague slate
#

I was thinking about tracking occupied AABBs

#

so then I could generate one big occupied AABB

fervent furnace
#

do you know what is free list? i just steal the idea from malloc

vague slate
#

and find space nearby

#

Nah, I don't

#

most of your thougts out load are gibberish to me 😅

#

someone tipped me about Rectangle Packing

fervent furnace
#

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....

vague slate
#

how do I figure how I subdivide?

#

also, should have mentioned. Space in the middle must be pre-allocated

#

basically it's more like

fervent furnace
#

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
late lion
#

@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?

vague slate
#

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

fervent furnace
#

if moving allocation is allowed, it is a garbage collector....much harder than plain malloc

vague slate
#

it's not

late lion
# vague slate it's not

And no requirements for how the allocations should ideally be arranged? Your example showed them crowded towards the top left corner.

vague slate
#

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

late lion
vague slate
#

so, what do I start with then?

#

as in, do I just have 1 big deallocated bound?

late lion
vague slate
#

it's not exactly box, it' smore like many boxes

late lion
vague slate
#

but to simplify I guess I could just round it to box

late lion
# vague slate 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.

vague slate
#

original space is 20k and mostly allocations are going to be about 200x200 or less

late lion
#

Are the allocations always square?

vague slate
#

no

#

but to simplify algorithm we can round them up

late lion
#

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.

vague slate
#

yeah, that's something at least

late lion
#

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.

vague slate
#

good enough for start

late lion
#

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.

fervent furnace
#

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

late lion
late lion
vague slate
#

Many scenes will be loaded multiple times for it

late lion
#

This assumes the rectangles can't be reoriented for ideal packing, though.

vague slate
#

they can't be

fervent furnace
#

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.....

late lion
vague slate
#

potentially it can

#

we move scenes anyway

#

just not as of now

mild sand
#

@swift falcon can you help me

vagrant drum
#

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

main shuttle
#

Can you show a screenshot in your IDE showing that the class name and file name are the same?

vagrant drum
#

sure

main shuttle
#

Hmm, it doesn't derive from monobehavior though. Not sure if this is allowed.

vagrant drum
#

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

main shuttle
vagrant drum
# main shuttle No not really, I'm scanning the docs but this addon seems ancient. But I don't ...

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

#

the component showed up to me before

#

but now it doesn't

main shuttle
#

Well, that's NavigationCollectSources2d, that seems like a different script.

vagrant drum
#

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

main shuttle
main shuttle
vagrant drum
main shuttle
# vagrant drum 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.

vagrant drum
main shuttle
# vagrant drum

Can you show a screenshot of your Console then? Did it even compile?

vagrant drum
#

yeah, it is clear

#

but a error appears when i run it

amber sinew
#

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

main shuttle
#

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.

vagrant drum
brittle oyster
#

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

#

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

brittle oyster
#

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

inland tendon
#

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?

fringe ridge
#

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

knotty sun
fringe ridge
#

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

somber tapir
#

any while loops in your code?

fringe ridge
#

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?

spring creek
fringe ridge
#

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

somber tapir
fringe ridge
#

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();
spring creek
fringe ridge
#
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;

spring creek
fringe ridge
#

i just moved the yield return to top

quaint crypt
#

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.

leaden ice
#

Probably just the ide being out of sync

quaint crypt
gray mural
#

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

rigid island
#

why wouldn't you wanna use a struct

#

they are awesome

leaden ice
#

Vector2 is a run of the mill struct

gray mural
#

apparently, wasn't that hard to create

leaden ice
#

they are not hard to create, no

gray mural
#

thank you for the tip 😄

simple egret
#

Consider overriding Equals and GetHashCode if you're going to do equality checks on them, and storing them into collections

latent latch
#

structs are nicer anyway because accessing stuff item1, item2, ect is uggggly

spring creek
latent latch
#

oh really ok I take that back then

spring creek
#

I still prefer structs though haha

dusky lake
#

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

heady iris
#

the fact that only one (and not two) bullets goes exactly straight forward makes it a little more annoying to set up