#archived-code-general

1 messages ยท Page 442 of 1

fading swallow
#

I've not heard of the physics queries, and, I thought using physics like that was too computationally expensive. Anyway, this is for a class assignment due today, so not enough time for a complete overhaul. I am trying to add a new collider I can reference in the inspector as a SerializeField, but the field is not showing

rigid island
#

Collider field should work just fine in inspector, how exactly do you plan on using that to help though ?

fading swallow
rain minnow
fading swallow
rigid island
#

code should be posted using links ๐Ÿ‘‡

tawny elkBOT
pastel cosmos
pastel cosmos
#

i wanted to know if maybe i can upgrade it and make cleaner

rigid island
#

Another thing you should probably do is apply rigidbody forces in FixedUpdate

round veldt
#

Hi! Sorry if this is the wrong channel, I'm not quite sure where to put it. Iโ€™m working on a Unity UI system where a shop item can be dragged and dropped onto a border collider to trigger an action. The drag works, but the trigger doesn't fire at all.

Iโ€™m dragging a UI element (inside a Canvas) using IBeginDragHandler, IDragHandler, etc.

That element has:
Rigidbody2D (Dynamic)
CircleCollider2D
CanvasGroup
Script with OnTriggerEnter2D(Collider2D other)

The border collider it should trigger has:
BoxCollider2D (Is Trigger โœ…)
Rigidbody2D (Dynamic)

Both objects are on Z = 0
I'm using Physics2D, not 3D
The dragged object is a child in a prefab, instantiated into the scene before dragging
The drag works, and the object moves correctly, but OnTriggerEnter2D never fires
I added debug logs โ€” nothing appears

This is the part that isn't working:
private void OnTriggerEnter2D(Collider2D other)
{
    Debug.Log($"Triggered with: {other.gameObject.name}");
    ShopManager.current.ShopButton_Click();

    Color c = img.color;
    c.a = 0f;
    img.color = c;
}
fresh sandal
#

hey I followed your instructions, it works amazing now! Thanks!

#

Now I have to find a way to keep the shadows static....

sterile reef
#

sweet!

fresh sandal
#

Not sure if I want the shadows anyway, oh welll...
Actually, I think I will tackle the shadow missing problem later

#

Light is such a pain to handle lol

sterile reef
#

instead of disabling the gameobject you can make a new layer WallHide and exclude it from your camera

#

by setting the layer of the gameobject to be hidden

#

though i dont know if that also takes away shadows

fresh sandal
#

Interesting, lets see....

#

Nah, that did not work. Worth the try though

#

It seems I need to use the ShadowCaster layer trick

thin pecan
#

It didnt work but thanks

rain minnow
civic girder
#

I'm working on a multi-step (few steps at most) action system for a grid based TRPG.

At each step of the action I want different things, example:

1) highlight valid tiles
2) if tile is clicked, do something
3) show a menu for the attack action if attacking is possible (ends a unit's turn) or just end a unit's turn

The issue is:
I want to allow the user to undo as long as the unit's turn is not ended (while they're still in the action).
This undo "reverts" back to the previous state.
However, I'm not sure how to do that.

Right now this is my pseudo code:

/// <summary>
/// serves as a memory for the action's stack. Helps with chain and undoing
/// </summary>
private struct ActionState
{
    public Action doAction { get; private set; }
    public Action undoAction { get; private set; }

    public ActionState(Action doAction, Action undoAction)
    {
        this.doAction = doAction;
        this.undoAction = undoAction;
    }
}

public override void TakeAction(GridPosition position, Action onMoveCompleteDelegate)
{
    ActionStart(onMoveCompleteDelegate);
    var initialState = new ActionState(() =>
    {
        //do
        MoveUnitToPosition(CastingUnit, position, CastingUnit.GridPosition);
    }, () =>
    { 
       //undo, do the reverse of the Do lambda
        MoveUnitToPosition(CastingUnit, CastingUnit.GridPosition, position);
    });
    // do the step and add it to the stack
    initialState.doAction?.Invoke();
    stateStack.Push(initialState);
    //create another state and show a menu
    PromptAfterMoveAction();
}

//called when the player presses the cancel button
public override bool CancelAction()
{
    //if no states exist, assume canceled
    if(stateStack.Count == 0) return true;
    var state = stateStack.Pop();
    state.undoAction?.Invoke();
    //indicates that all steps have been canceled
    return stateStack.Count == 0;
}
#

It works so far (early prototyping), but given that some of the logic involves UI (menus, highlighting grid tiles, etc), I'm not sure if this solution would bite me later.
I'm not looking for full-code solutions on here, I'm aware that this is specific to my design system, but what should I look into when dealing with such a mechanic?

karmic stone
#

Hello! I'm currently coding some interaction with unity's terrain using code and scripting api. (Heightmap, 2d float array specifically) I'm trying to get all points in the grid array thats between a min/max point given to the function as a float, and minus some area from their height. however, when doing this, i cannot get why my code, which is min inclusive, maxexclusive, creates a "grid square" that is so much smaller then the bounds that was passed, could anyone give me an opinion on what i did wrong? https://paste.ofcode.org/T2gaEzjbwhL2ahGBKYsKyh
I know that the grid array index is cell - 1, but then the cast means that every part is always the cell below where the area is. cell -1 (for index) then +1 (because i dont want to edit things outside the bounds) for min. for max, its exclusive, so i want it to be 1 above whereever the last index to change is. -1 for array index, and then +1 because i want to edit things right below max value.

copper inlet
karmic stone
steady bobcat
karmic stone
steady bobcat
#

does that green gizmo match the mesh change? again i cannot tell ๐Ÿ˜†

#

btw you can use Vector2Int if you wish and id use many args instead of a Tuple here

karmic stone
#

heres another screenshot, and i do use vector2int, once i convert the floats to ints.

#

that green matches the minx,miny, maxx , maxy calculated in GetMinMaxHeightIndexes

#

the red matches the area tuple given as an arg to the GetMinMaxHeightIndexes

#

the green SHOULD be the Minx/y closest to the minx/y of the area, and the maxx/y closest on the outside of the bounds.

steady bobcat
#

new Bounds(minCellWorld + (maxCellWorld - minCellWorld)/2, (maxCellWorld - minCellWorld)/2)
here you half the size too?

#

and go ortho in scene view to make this not shit to look at plz

karmic stone
#

new bounds(center, extents), center being min + max - min /2

steady bobcat
#

its size not extents?

karmic stone
karmic stone
#

ahh, dumb of me. thank you

steady bobcat
#

you can make your life easier by making this a vec sooner and doing a vec/vec or vec * vec operations btw

#

also you can do (Vector2Int, Vector2Int) to do a tuple

karmic stone
#

Ahh, do it right after minusing the transform.position, thank you rob.

steady bobcat
#

no prob

karmic stone
#

Well, fixed the issue, problem is im trying to do this with a big terrain, creating a smaller terrain with same detail makes my hoeing HIGHLY more accurate

cloud tundra
#

Im setting up procedural room generation with prefab rooms, but i am currently try to avoid overlap with box colliders, but this currently just stops generating any room as it some how detects overlap

cloud tundra
cloud tundra
leaden ice
#

code, screenshots

#

you can make a thread here

cloud tundra
#

Procedural Generation Issues

young yacht
#
if (Gamepad.current == null)
        {
            screenMouse = playerInput.UI.Point.ReadValue<Vector2>();
        }
        else
        {
            screenMouse = Mouse.current.position.ReadValue();
        }

        screenRay = Camera.main.ScreenPointToRay(screenMouse);
        crosshairRect.transform.position = screenMouse; 

        timePlayed = Time.realtimeSinceStartup;
        aimRig.weight = Mathf.Lerp(aimRig.weight, aimWeight, Time.deltaTime * aimSpeed);

can anyone help here? i got a virtual mouse script on my crosshair and i'd like to use the gamepad right stick to move that same crosshair, its working but thing is when i stop the stick motion it snaps back to the left screen corner

#

i might be overriding something

civic girder
vestal arch
#

it can't be unset

civic girder
#

yes

#

hence getting on the left bottom side, an easy way to fix this is to only call the logic:
crosshairRect.transform.position = screenMouse;
IF the cursor/gamepad actually moved.

IIRC, for Mouse, there is a "hasMouseMoved" method or something like that, returns a bool if it has moved or not. (If not, get the mouse delta and check that it is not 0,0)

#

I'm not sure about gamepad, you might need custom logic if such a method doesn't exist

vestal arch
civic girder
#

personally no, but sometimes it's good to support different input methods.

In disgaea 5 for example, I played it mostly via keyboard
However, when I'm eating/feeling lazy, I just play with mouse while using my other hand to eat or rest.

So I'm not questioning OP's logic, he just needs better handling

vestal arch
#

....are you answering me?

#

im not asking you

civic girder
#

I know

vestal arch
#

no clue what you're trying to say then lmao

young yacht
#

was testing to see if the problem was using the same input

#

still snapped

young yacht
vestal arch
# young yacht if gamepad is null

look at your code again
if Gamepad.current is null, you read playerInput.UI.Point
if it isn't, aka there is a gamepad, you read Mouse.current.position

young yacht
#

sorry

#

was looking at a more recent version on my screen

young yacht
#

was looking at this

vestal arch
#

gotcha

young yacht
#

i also checked unity's virtualMouse script and found a function they use to update the motion

#
if (Mathf.Approximately(0, stickValue.x) && Mathf.Approximately(0, stickValue.y))
            {
                // Motion has stopped.
                m_LastTime = default;
                m_LastStickValue = default;
            }
            else
            {
                var currentTime = InputState.currentTime;
                if (Mathf.Approximately(0, m_LastStickValue.x) && Mathf.Approximately(0, m_LastStickValue.y))
                {
                    // Motion has started.
                    m_LastTime = currentTime;
                }
#

i thought the problem was that m_LastTime = default

#

tried commenting that code but its still snapping

vestal arch
#

have you tried debugging the values you get from that?

#

are you sure it can read directly as a pointer?

young yacht
#

yea good idea

#

let me try

young yacht
vestal arch
#

...no clue what you mean by that

young yacht
#
if (Mathf.Approximately(0, stickValue.x) && Mathf.Approximately(0, stickValue.y))
            {
                // Motion has stopped.
                m_LastTime = default;
                m_LastStickValue = default;
                Debug.Log(m_LastTime);
            }
            else
            {
                var currentTime = InputState.currentTime;
                if (Mathf.Approximately(0, m_LastStickValue.x) && Mathf.Approximately(0, m_LastStickValue.y))
                {
                    // Motion has started.
                    m_LastTime = currentTime;
                    Debug.Log(currentTime);
                }
young yacht
vestal arch
#

why are you debugging the time

#

oh i wasn't specific when i said to debug "the values", sorry

vestal arch
young yacht
#

mouse values

#

gamepad values

#

maybe best way really is to just have a boolean check if the stick is moving

vestal arch
wise kindle
#
using UnityEngine;

[System.Serializable]
public class Connection 
{
    public Node from; //The node where the connection starts
    public Node to; //The node where the connection ends

    public bool bidirectional;
    public float weight;

    public Connection(Node from, Node to, bool bidirectional)
    {
        this.from = from;
        this.to = to;
        this.bidirectional = bidirectional;
        this.weight = Vector3.Distance(from.position, to.position);
    }
    public Connection(Node from, Node to, float weight)
    {
        this.from = from;
        this.to = to;
        this.weight = weight;
        this.weight = Vector3.Distance(from.position, to.position);
    }

}```

This is a Connection Class, there is also a Node class that has a Connection list in it, the issue with the Connection list within the Node class is that it causes infinite nesting, which severely damages performance in unity, how could I avoid this infinite Connection nesting?
placid edge
#

how do i make a raycast ignore all collisions except two types of objects/layers?

vestal arch
placid edge
# robust dome you can use a layermask.

they also have different layermasks, basically i want to make an enemy that doesnt notice the player if there's another enemy standing between them, but in doing so and setting the layermask to enemy it's detecting itself as they are all copies

vestal arch
robust dome
#

you could simply use a CompareTag and see if it hits the enemy or player

#

then you would have to do what Chris recommended so that your rc is outside of your own collider

#

this should do the trick.

woven pendant
spice estuary
#

Kinda hard to tell without knowing what your Ship script is doing

woven pendant
#

its just rotating the ship gameobject

#

it has children with rigidbodys, no gravity

#

and im testing now and its like the velocity is not local

spice estuary
#

If you change the transforms of a parent, the children will be affected

woven pendant
spice estuary
#

Dynamic rigidbodies don't really go well with parent/child relationships

#

since they are simulated through physics

woven pendant
#

oh

placid edge
# robust dome this should do the trick.

it would work that way but the problem is that I have a lot of colliders on my 2d scene, and i need the Raycast/Linecast to ignore those and keep going until it meets either another enemy or the player. Some of these colliders also have their own layermasks ;/

spice estuary
#

That's what the layermask is for. You tell the raycast to test against colliders that are included in the layer(s). Then you can filter anything you want. If the enemy casting the ray is hitting itself, then move the raycast start position so that it isnt inside the source

#

Alternatively you can use raycastall which doesnt stop when it hits something, but instead returns everything it hits, then you can check what it hit and filter as you need there. A standard raycast is cleaner though, if you can make it work where it doesnt hit the source caster

placid edge
#

yes this solution is working much better thanks, the problem wasnt that it was hitting itself itsthat there's a lot of colliders in the scene it can hit that i dont want it to, so getting them all and filtering it until and if it finds an enemy is the way to go for me

spice estuary
#

Then supplying only the Player and Enemy layermask to the raycast should do the trick

placid edge
#

how do i do both of them, I can see that i can feed it an int that would serve as the number of the layermask, how would i be able to give it both numbers?

spice estuary
#

You can create a serialized field for example:
public LayerMask hitLayer;

#

then in the inspector it will show as a dropdown where you can select multiple things

#

then in the raycast you feed it the hitLayer where it asks for the layermask

placid edge
#

ive tried that but couldnt get it to work, where would I dynamically change the layermask?

#

i previously put it inside where it would detect that it hit said layer

spice estuary
#

It's something that is usually predetermined. For example if I have a script for an enemy that performs an attack, I have the serialized field already set inside the class

#

then in inspector I would assign which layers this attack should be able to hit

vestal arch
placid edge
#

yes, the order of the layermasks no?

spice estuary
#

Think of it as a whitelist you give the raycast

vestal arch
#

a layermask of 0 means nothing
a layermask of 1 means layer 0
a layermask of 2 means layer 1
a layermask of 3 means layer 0, 1
a layermask of 4 means layer 2

vestal arch
#

i think you're confusing 2 terms, you're calling "layers" and "layermasks" both as "layermasks"

placid edge
#

ah, it doesnt start at zero

vestal arch
#

it doesn't start at any value

#

it just is a value

#

or you could view it as being many values

spice estuary
#

It's easier to just think of it as a list of Layers

#

the raycast checks all colliders with the layers included in the mask

vestal arch
placid edge
#

wait a minute, so because the raycast is always aimed at the player, if i simply check to make sure that there isnt an enemy in the way, then that would work?

spice estuary
#

Yes that could also work

#

It depends what you use it for

#

If you need to know where you hit the player you would still need to include the player

placid edge
#

so i can just set the layermask to enemy and that should work? i think i just complicated this for myself for no reason ๐Ÿ˜ญ

spice estuary
#

Yes

#

anything you put in the layermask, is what the raycast will do hit detection for

placid edge
#

yes i think i overcomplicated it by thinking i needed to detect the player when its already aimed at the player and can simply do a function somewhere else if raycast doesnt detect an obstacle, of which it would only be an enemy

placid edge
#

youre right i dod confuse layers with layermasks

#

what layermask would i need to use to get the 6th layer which would be the Enemy Layer

#

or is it something completely different

spice estuary
#

It's easier to just to make a public or serialized layermask variable ๐Ÿ˜„

#

then you have a nice UI where you select which ones it should be, and the nice magic works out the bit shifting for u

placid edge
#

ok im gonna have to look this up

spice estuary
#

Feel free, I almost never need to know the nitty gritty for what I've used raycasts for, but it can be very efficient in general for flags and other things

vestal arch
#

the former would be 128, the latter would be 64
but really you should just use the inspector UI to set it, much easier

vestal arch
placid edge
#

its just hard to grasp for me ๐Ÿ˜ญ

#

its the layer number 6

#

so... layermask 64?

#

should I just write 64 then? its not like ill shuffle my layers around any time soon

vestal arch
placid edge
#

no i didnt lemme scroll up

vestal arch
placid edge
#

wait youre so right

#

i did that before

#

godammit

vestal arch
#

....we've been telling you to do that the entire time tho?

placid edge
#

i have problems understanding things at times

#

;/

#

yep, works like a dream, thanks guys catto

#

cant believe i kind of had it at one point and deleted it all before coming here smh my head

hardy pasture
#

How to hide game objects in a generic way, similar to how when you press the eye button in the inspector?

last quarry
last quarry
#

Will need to disable the renderers then

hardy pasture
#

Also I want it to work in the editor: how when you press the eye symbol.

hardy pasture
#

Also when I press on the eye in the editor, it doesn't seem to disable the images either but everything is not visible.

last quarry
#

So on a canvas?

hardy pasture
#

Yes, but not necessarily, I guess.

last quarry
#

Add a canvasgroup, make it transparent

naive swallow
#

Quick question about GLTFast - the documentation is creating a new GltfImport every time a file is loaded, but doesn't seem to use it after the .Load call. Is that necessary or can I re-use the same one if I have to load multiples? The documentation isn't clear either way - it just does them in every section, presumably to make each piece a self-contained snippet of code.
https://docs.unity3d.com/Packages/com.unity.cloud.gltfast@5.2/manual/ImportRuntime.html

naive swallow
#

Guess I'll just have to tryitandsee, but for that I need to actually get it to run multiple imports.

Previously, I was doing this with a Coroutine, but Gltfast is expecting async, and I'm not entirely sure how to "kick off" an async. I get the general concept of it, and I've used it before with async Start and the like, but this one needs to fire when a variable changes (a string representing a directory full of GLTF assets to scan through) which is done in the UI. I have the event and everything all wired up, the user picks a directory and it goes to an ordinary function OnPathChanged, which used to use StartCoroutine to kick off an IEnumerator that loaded the assets one at a time. But now that LoadMeshes function is an async Awaitable LoadMeshes instead. How do I kickstart an async outside of another async?

steady bobcat
naive swallow
steady bobcat
#

you surely can

#

async is not like a coroutine where it needs special handling to make the yielding work

naive swallow
#

I don't need this function to do anything after starting the task, I just need it to fart in an elevator on its way out. The task will start loading in the meshes as it goes and fire off events, isn't there a way I can have synchronous code just, queue and abandon an async?

steady bobcat
#
public async UniTask MyCoolAsyncFunc()
{
    await UniTask.Delay(100);
    Debug.Log("foo");
}

MyCoolAsyncFunc();
//do other stuff
#

ha got there in the end

#
MyCoolAsyncFunc().ContinueWith(() => Debug.Log("I get called after this is done"));
naive swallow
#

So, this warning can just be ignored? If I don't care about the results of this function I can just call it like this?

steady bobcat
#

yes

naive swallow
#

Neat

#

I can assign it to a discard to avoid the warning, it looks like

steady bobcat
#

If you use UniTask you can use .Forget() to make it shut up and log exceptions correctly
You may notice that if it throws an exception it wont be logged until you stop playing.

#

Unity are dumb and added Awaitable too late hence many of their packages use Task when you should not use it in your own code

#

I use UniTask in projects I work in

naive swallow
#

Does UniTask work with await Task.WhenAll?

steady bobcat
#

It has its own version

naive swallow
#

Okay, I'll see about getting that

steady bobcat
#

Also has helper functions such as:

someUnityEvent.AddListener(UniTask.UnityAction(async () => {}));
naive swallow
#

But as it currently is, Awaitable seems to not be doing anything. I'm gonna do some debugger time and see if that's my fault in the function itself or if it's just not starting the task

steady bobcat
#

avoid doing _ = AsyncThing(); and do AsyncThing().Forget() and also debug to see whats up

naive swallow
#

Okay, it seems at some point in my thread, an exception just gets lost to The Void

#

I was clicking through it and my entire debugger context just vorped into nothing

#

I'll go get UniTask

steady bobcat
naive swallow
#

Yeah, I've stepped on that particular rake before so I knew what to expect when it just silently died. I just kinda need the error to know what went wrong

#

So I'm gonna try out this UniTask thing

#

I have a TaskScheduler.FromCurrentSynchronizationContext() that uses the System.Threading namespace, can I just keep that or is there a UniTask equivalent?

blazing wyvern
#

I just spent 40 lines of code on an ADS script and i was just told about ternary operators

#

Apparently i could do it in like 10 lines

#

What the fxck

naive swallow
blazing wyvern
steady bobcat
#

UniTask should be using the unity task scheduler already but they use their own things also using the update loop.

blazing wyvern
#

But it still bugs me how easy it could've been instead of me overcomplicating everything

#

I also learned about coroutines today :>

#

Probably the most useful thing i've encountered in a while

naive swallow
steady bobcat
#

Ah, you can use .ToUniTask() and then continue with and not worry

#

Or in the continue with you can use await UniTask.SwitchToMainThread();

naive swallow
steady bobcat
#

the delegate can be async.

Actually im not 100% on if unitask will use the unity scheduler automatically ๐Ÿค”

steady bobcat
#

tis a pain managing this sometimes

#

Ha guess there is one

naive swallow
#

Aha! There you are you little exception

#

Now, to find out what it means

steady bobcat
#

Yay progress

naive swallow
#

Okay, found the source of the error

naive swallow
#

Okay, good news: Async stuff works like a dream, got all the meshes streaming in just as I'd expect.

Bad news: For some reason every east/west facing wall has been infected with a poultergeist

#

Almost certainly something wrong with my import settings from gltfast, kind of looks like mipmaps gone haywire? Maybe shadows?

#

It's the Triplanar shader I wrote negativeman

No idea why it worked with the TriLib imported mesh but not Gltfast but it certainly does seem to be a me problem, guess I have to go figure it out

hexed pecan
naive swallow
#

Would explain also why it happens only on walls in a very specific orientation

#

How would I compute the tangents of a triangle, given the vertices and normals?

#

Looks like I need the Cross Product of the normal and world up?

#

So now I need to actually learn how to do a Cross Product because my mesh source does not have a convenient Vector3.Cross method

steady bobcat
#

If you can get it after loading that is

naive swallow
#

I probably could, but I think GetComponenting the mesh filter and pulling the mesh from it would be a significant drain on resources

#

but maybe there's somewhere further down the pipeline where I do have access to the mesh that I can do? A few frames of static is acceptable if it "pops in" later

steady bobcat
#

Why? It's already a mesh on cpu side and seems like you need to fix this

naive swallow
#

Success! I found somewhere later on in the processing chain that got the mesh filter and just slapped a RecalculateNormals function there and no more static

naive swallow
steady bobcat
#

Oh right I see, I presumed it was a few only

#

Where are the glb files coming from?

naive swallow
#

No, it's like, thousands. And GLTFast gives me the whole instantiated objects, not the meshes themselves

naive swallow
steady bobcat
#

Probably the normals are bad? I forget if tangents are calculated or are imported

naive swallow
#

The normals seem fine, problems with those would be visible in the lighting. It's definitely my math because I'm forced to work in a really janky psuedo-vector data structure that sucks and has zero convenience functions

reef garnet
#

anyone here know how linearDamping applies to a rigidbody, like when calculating the resultant force how does it affect that equation

vestal arch
reef garnet
#

hey thanks

naive swallow
#

So, now that I've got this fancy UniTask library, is there a way I could use it to queue up multiple functions, and run as many of them per frame as it can while keeping up a certain framerate? I have a bunch of stuff that uses AddComponents and other UnityEngine functions, so I can't offload it to another thread. Still, I'd like to make sure the framerate stays as close to 30 while loading them as possible. In a Coroutine, I'd keep a running tally of how long it's taken to execute each function and yield return null when that timer goes over 33ms. Is there a better way to achieve this with UniTask?

steady bobcat
naive swallow
#

Which would be perfect if I could multithread these

steady bobcat
#

well you can delay for an amount of frames so technically you could yourself "queue" up work over many frames at once

naive swallow
#

Yeah but the amount of time they take isn't always static

#

some of the calls have to do a lot more heavy lifting than others

#

"Run as many of this as possible without dipping below X framerate" seemed like a common enough use case that I thought UniTask might have a system for doing so other than Stopwatches and Yields

steady bobcat
#

Its probably an over step(for UniTask to provide this) but you can surely make your own utility to run a set of Func<UniTask> and wait till another frame between if some time limit is reached.

chilly surge
#

Are you doing something that must be done on main thread? Because otherwise you could just put everything in a background thread and let it run as long as needed.

naive swallow
chilly surge
#

Yeah I don't think there's something built in, but you could make a method that returns Time.realtimeSinceStartup - Time.unscaledTime > budget ? UniTask.NextFrame() : UniTask.CompletedTask.

steady bobcat
#

I wouldn't do it this way but as I suggested if you wish to avoid placing checks everywhere

naive swallow
#

Basically, I wrapped the expensive-ass function in this:

Stopwatch timer = new Stopwatch();
timer.Start();
long currentTime = 0;
foreach(...){
  long startMills = timer.ElapsedMilliseconds;
  ExpensiveAssFunction();
  long endMills = timer.ElapsedMilliseconds;
  currentTime += (endMills - startMills);

  if (currentTime > 33)
  {
    await UniTask.Yield();
    currentTime = 0;
  }
}
#

I'll un-magic that number if this works

chilly surge
#

It's actually worse if you need to pass values from one function to the next.

chilly surge
night hearth
steady bobcat
#

Well they kinda wanted it to be automatic so do you

chilly surge
#

You have to manually decide where is an acceptable place to break into next frame, no matter the approach.

naive swallow
#

That's certainly more automatic than what I have

chilly surge
#

The difference is just "where do I manually insert await NextFrameIfOver(budget)" vs "where do I manually split this function into multiple parts."

naive swallow
#

I hadn't thought of just using unscaledTime as the benchmark... that's a good idea. Lemme give that shot

rigid island
thick terrace
# naive swallow That's certainly _more_ automatic than what I have

one slightly more automatic way i've done this in the past is writing the method in question as a coroutine, then instead of running it directly, make a wrapper method that takes an IEnumerator and iterates through it step by step and waits as necessary between steps. it's not much more automatic than the above, but it means you don't have to actually put any timing specific code in with the real work, just yield return null and let the wrapper method decide what to do, so it's really easy to do things like vary the rate or do other stuff between steps

hot ledge
#

I'm trying to set the color of specific sections of text in a TextMeshProUGUI component using scripts, but I'm struggling to get it working. The most I've been able to do is change the color of the text's underline.

https://codeshare.io/5zEor2

leaden ice
hot ledge
leaden ice
#

It should work fine ๐Ÿค”

hot ledge
#

like I said, it only changes the underline

leaden ice
#

maybe an issue with your font or something? ๐Ÿค”

#

What if you do it on text that isn't underlined?

#

does it work then?

hot ledge
#

nothing then

leaden ice
#

What if you switch fonts

hot ledge
#

but, the colors do change if I mess with the vertex color

hot ledge
leaden ice
#

Sure but

#

just for the sake of figuring out the problem

#

an you try the default font for example

#

If that also doesn't work then we can at least rule out the font as the issue.

hot ledge
#

issue persists it seems

leaden ice
#

Strange. I've never had an issue with this ๐Ÿค”

#

What if you try to change the order of the nesting of the tags?

#

For example instead of <color><u>text try <u><color>text

narrow sapphire
leaden ice
#

aalso a good idea^

narrow sapphire
rain minnow
narrow sapphire
#

So you can change the colour of only the underline

hot ledge
naive swallow
leaden ice
# hot ledge

silly question what if you try this in a separate completely empty scene

#

Just put a TMP_Text in it alone and play with the font and tags

#

delete all other objects

#

Also make sure to look at it in Game View not just scene view

hot ledge
#

oh wait I think I figured it out, Override Tags was enabled

narrow sapphire
hot ledge
#

yeh there we go

leaden ice
#

Ahh - I forgot about that checkbox

#

I do think that might be a bug though - the fact that it was coloring only the underline

hot ledge
#

Follow up question:
This text is inside a scroll box, I wanna have it set up so that the box automatically scrolls to the section of the text that's highlighted whenever it's enabled. How would I do that?

#

would it be possible to grab position values from the vertex index of a character or something similar?

rain minnow
naive swallow
narrow sapphire
steady bobcat
#

You can get text info about the whole thing and set the relative scroll pos but finding where the text is im not sure ๐Ÿค”

hot ledge
narrow sapphire
#

No can do then with this setup I think

#

Not easily at least

#

Why not make each conversation line separate and spawn them all in when needed

hot ledge
#

because 50 gameobjects being instantiated into a single text box will lag my quest 3 lol

narrow sapphire
#

Then you can reuse the same ones

#

No need to create and destroy gos yeah ur right tbh

hot ledge
#

I tried that with a different thing in my scene, an ingame debug output view with 100 components

rain minnow
hot ledge
#

it was responsible for like half of all of my performance issues lmao

chilly surge
#

Not sure about TMP, but UGUI text has a TextGenerator, you can use that to grab all the positions of characters and lines.

narrow sapphire
#

If performance is that tight that you canโ€™t handle 20 gos for 20 bits of ui text then idk

hot ledge
narrow sapphire
#

Is it necessary to have the entire conversation at once?

hot ledge
#

nope, it's already split into pages

narrow sapphire
#

A solution if itโ€™s ok is to just split up the conversation

#

More

#

Important highlighted text could even be its own conversation turn

#

Makes sense if itโ€™s important

hot ledge
#

with a max line count of 50 I'm already getting 32 pages of text in some places lol

narrow sapphire
#

From a player standpoint itโ€™s a bit of a flash bang to get all this text

#

At once

#

More easily engagable if itโ€™s a few lines max at a time

#

VN style

hot ledge
narrow sapphire
#

Yes I just saw this on docs while looking through

#

At same time haha

#

If you like foreach var wordinfo

#

Check for the text you need

#

Then get first character position

#

Should work

#

Surprised that exists actually

steady bobcat
#

yea you can loop until you get a match over a range of characters and then use the first to calculate the new scroll pos

hot ledge
#

yeah I think that's working, it seems to be localPos

#

gotta edit my code's logic a bit to actually get the correct character index but I'll try it

narrow sapphire
#

WordInfo.textcomponent.m_fontColor might be easiest

#

Thereโ€™s like a gazillion properties in this TMP_Text class

#

Ah thereโ€™s one thatโ€™s just textcomponent.color

steady bobcat
#

If you can insert your own tag and find that then that would be a clean solution
using colour seems bad

#

yes we know its coloured yellow but its not very reliable vs an exact string match or pre determined char index.

narrow sapphire
#

Lots more effort though

narrow sapphire
#

Nevermind there is actually textcomponent.string

#

All the way at the bottom of this 300 entry properties list

chilly surge
#

Not surprised that mesh info is exposed especially since UGUI text also exposes it.

narrow sapphire
chilly surge
#

I've always wished instead of some weird BBC custom format they use for rich text, they would just expose the internal AST.

narrow sapphire
#

There might not be any way to distinguish without using color or some other actual property of the text

chilly surge
#

Trying to sanitize user content by escaping the BBC tags is hacky and weird, and there are quite a few of Unity games that they just don't bother and you can use BBC tags to change your user name colors and what not.

steady bobcat
#

oh shit you can get link info so you could use this to easily find the character positions for the headings

#

presuming these can be made to not change the text style

hot ledge
#

hmm.. I can't seem to figure out how to get the right character index

#

I'm currently doing it by just noting the length of the string one I find the line to highlight

#

but that apparently doesn't line up with the actual character indices in the textbox

#

seems like the string length is always longer than the length of the characterInfo array

steady bobcat
#

it surely wont include the tags so the rendered characters len will be less than the input string...

narrow sapphire
#

I think string excludes the tags tho

#

The scripting docs said โ€˜string to be displayedโ€™ or something like that

steady bobcat
#

i presumed they were checking the original but you can just loop till you hit a char info matching char 0 of some string and keep going till you get a full match

#

you just need to know the thing to find such as "foobar"

hot ledge
#

oh wait one of the characterInfo properties is lineNumber

steady bobcat
#

๐Ÿ˜ well

vagrant blade
#

@stark scroll !collab

tawny elkBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
โ€ข Collaboration & Jobs

mild goblet
#

Iโ€™m getting a Box Collider from a GameObject on awake and I get this error :

ArgumentException: GetComponent requires that the requested component โ€˜BoxColliderโ€™ derives from Mono

#

If anyone is getting a box collider show me how please.

west lotus
#

Show your code first

mild goblet
west lotus
#

Have you made a class called BoxCollider this looks otherwise ok to me

surreal basalt
#

hello, im trying to set vsynccount to 2(every second v blank) to lock my game at 30 fps on console, but it caps to 60 fps instead

#

when i debug the setting it clearly shows that its 30 fps/every2ndvblank

#

can it be a problem with TV somehow?

last quarry
#

Is the TV 120Hz?

#

Unfortunately I donโ€™t think thereโ€™s a way to reliably cap framerate in Unity while maintaining vsync

vestal arch
tawny elkBOT
vestal arch
#

also, you're getting a runtime error?

mild goblet
#

i'm going to try to access the collider through ECS

west lotus
#

Oh you mean you are using a EntitiesPhysics.BoxCollider ?

glass swan
#
  {
      case NodeManager.EResult.POSITIONAL:
          lResult.directory = lNode.Directory;
          lResult.windowFromDirectory = lNode.WindowFromDirectory;
          goto case NodeManager.EResult.NON_POSITIONAL;
      case NodeManager.EResult.NON_POSITIONAL:
          lOutput = lNode.AccessText;
          lWaitingPrefix = Format(lNode.WarpingText, input);
          break;
      case NodeManager.EResult.EVENT:
          lOutput = "Event sent successfully!";
          break;
      case NodeManager.EResult.MAIL:
          lOutput = $"QuickMail received: {lNode.name}";
          break;
      case NodeManager.EResult.FAIL:
          lNode = NodeManager.Instance.Current;
          lOutput = lNode.KeywordFailText;
          break;
   }```*
#

Hello!

#

I haven't found a way other than "goto" (which I never had to use before) for putting code in a case, while keeping the behavior that we have by chaining 2 cases

#

Is there a better way? ๐Ÿค”

surreal basalt
#

on ps console it works fine tho

vestal arch
glass swan
#

Oh so it seems like it is the way. Thank you for the help ๐Ÿ™๐Ÿผ

#

And as I see it isn't even a true goto ๐Ÿค” That's interesting, and very smart of them as the usage is still very reminiscent of goto

vestal arch
#

an alternative with an if-else chain is possible, but it's up to you whether you consider this a "better" way lol

  NodeManager.EResult result = NodeManager.Instance.TryRouteKeyword(input, out NodeInfo lNode);
  if (result == NodeManager.EResult.POSITIONAL || result == NodeManager.EResult.NON_POSITIONAL) {
      if (result == NodeManager.EResult.POSITIONAL) {
          lResult.directory = lNode.Directory;
          lResult.windowFromDirectory = lNode.WindowFromDirectory;
      }
      lOutput = lNode.AccessText;
      lWaitingPrefix = Format(lNode.WarpingText, input);
  } else if /* other cases */
glass swan
#

Ye, for these kind of things I find the switch cases more readable

mint bear
#

hello i have a super idea for video game but i don t know who insere this code so i give you the script and if you whant you insere this code a ok (sorry if i wartter not good )

#

ps i am make me help for chatgpt

safe flame
#

What

#

Also we don't help with chatgpt code

#

Or chatgpt anything

vestal arch
#

we're not gonna accept random files

#

also !collab

tawny elkBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
โ€ข Collaboration & Jobs

last quarry
robust dome
#

virustotal behaviour gives dangerous outputs

quartz folio
#

!warn 1088531099845664878 do not post suspicious files. There's absolutely no reason to post code as an odt file.
If you're seen doing similar in future you will be removed from the server.

tawny elkBOT
#

dynoSuccess momi1769 has been warned.

soft shard
last quarry
#

Application.targetFramerate is ignored when vsync is on

swift falcon
#

Hi!

steady bone
#

Hello everyone, Iโ€™ll try to keep it brief.
Iโ€™m currently working on a year-end project at my school and Iโ€™m using the MultiplayerService for sessions. The problem is that the schoolโ€™s internet connection is quite slow, so I canโ€™t create sessions and I keep getting timed out (knowing that it works fine at home or using 4G).
I wanted to know if anyone here had any workaround solutions that could help me out? (aside from being on 4G all the time).
Thanks a lot!

steady bobcat
#

Does it let you specify the timeout time?

steady bone
#

It doesn't look so bad at first glance, but the problem doesn't occur all the time, and in the evening when there are fewer people, it works without too much trouble.

#

My theory is that the client is trying to join the session when it hasn't been created

#

Since the function is in async

#

I don't have a lot of knowledge on the subject, so I don't have an overview, if someone can tell me the potential causes of this issues

narrow sapphire
#

From my experience in n4e the designs were such that that isnโ€™t possible

#

Idk if n4go is much different but Iโ€™d assume youโ€™d want the same

steady bone
#

I can show the networkhandler it is make by a friend

#

My bootstrap

#

And when i tried to connect on relaynetwork i receive all response but he doesn't found the joincode

robust dome
steady bone
#

Ah mb

lament estuary
#

Hello, with a friend we have a end of the year school project and we need to create a game, we have all the ideas but we have some trouble with our dash mechanic, it's working but not like we want, and we don't really know how to fix it, if somebody can help us we'll be thankful

mellow sigil
#

You'll have to explain how it works now and how you want it to work, and show the !code

tawny elkBOT
lament estuary
#

So basically, when we want to dash horizontally we just press Shift, and if we want to dash upwards we need to press Z, but we just want only one button to dash in every direction, sadly we cant find the solution
Here's the code (2 parts separated) : https://scriptbin.xyz/odixudatac.cs

Use Scriptbin to share your code with others quickly and easily.

vestal arch
lament estuary
vestal arch
#

i mean do you have the dash mechanic itself done?

narrow sapphire
vestal arch
#

you would just dash in the direction specified by wasd

narrow sapphire
#

And check holding space to dash up

lament estuary
#

Okay i'll try to do it like that, and tell you if it works

#

Thanks

neon plank
#

I have a little math problem and I'm having trouble solving it.
I have a character that must look up a target by rotating its neck (vertical and horizontal rotation). However necks has a limit and so I must to clamp it somehow.
I have this values:

  • A Vector3 baseDirection which is the base direction of the head (the "forward" vector).
  • A Vector3 targetDirection which is the (unconstrained) direction towards the target.
  • A float maxHorizontal which is the maximum number of degrees the head can rotate horizontally.
  • A float maxUpward which is the maximum number of degrees the head can rotate upwards.
  • A float maxDownward which is the maximum number of degrees the head can rotate downwards.
    And I must to use this in order to get a Vector3 newDirection which is the (constrianed) direction towards the target in which the character won't break its neck .
    But I don't know how to get that.

I was trying with:

Quaternion delta = Quaternion.FromToRotation(baseDirection, targetDirection);
Vector3 angles = delta.eulerAngles;
angles = Normalize(angles); // Convert range to [-180;180]
angles.y = math.clamp(angles.y, -maxUpward, aimingTargetMaximumHorizontalAngle);
angles.x = math.clamp(angles.x, -maxDownward, maxUpward);
Quaternion newDelta = Quaternion.Euler(angles);
Vector3 newDirection = newDelta * baseDirection;

But it doesn't work. I'm not sure how to solve this.

young yacht
#
using UnityEngine;

public class RepositionPlayer : MonoBehaviour
{
    //where the player should spawn
    [SerializeField] GameObject player;
    [SerializeField] GameObject repositionObject;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player");

        if (player != null)
        {
            Reposition();
        }
    }

    public void Reposition()
    {
        player.transform.position = repositionObject.transform.position;
    }
}

why is this simple script not working on build but works on development?

hexed pecan
steady bobcat
young yacht
#
using System.Collections;
using UnityEngine;

public class RepositionPlayer : MonoBehaviour
{
    //where the player should spawn
    [SerializeField] GameObject player;
    [SerializeField] GameObject repositionObject;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    IEnumerator Start()
    {
        yield return null;
        
        player = GameObject.FindGameObjectWithTag("Player");

        Reposition();
    }

    public void Reposition()
    {
        player.transform.position = repositionObject.transform.position;
    }
}
steady bobcat
#

why is player also serialized if you then find it by tag?

#

Finding by tag is un reliable and you should always prefer serialized fields of the needed component type when possible.
e.g. [SerializeField] Player player;

young yacht
#

its not manually referenced

#

hence the tag reference

steady bobcat
#

Perhaps a static reference to the player should be preffered then or you can better integrate this into your scene loading logic (e.g load scene, get spawn pos, move player to spawn pos)

#

Finding by name/tag is fine when a beginner but not a good practice long term

young yacht
#

hm i see

#

i'll check on static references

#

thanks!

steady bobcat
#

well if you have the ability to invoke an event and have the player listen then yea do that.
I like to have a component in newly loaded scenes (e.g. for a level) that is used to facilitate initialisation and setup (e.g. has ref to start pos and is directly read and applied to the player in level load logic)

steady bobcat
young yacht
#

sets up everything nicely on every scene start

young yacht
steady bobcat
#

Games I have worked on recently have a LevelLoadService (not mono) and a LevelInit and LevelController in the level scene. this is found by the service when the scene is loaded.

young yacht
#

this is my first proper project so its full of shitty practices

#

learned about C# events halfway through

steady bobcat
#

events are great. UnityEvent exists also which lets you serialize subscriptions in the inspector (has a cost due to needing reflection to resolve at runtime)

young yacht
#

i tried both but C# events just seem way more intuitive

#

and having to set up all events manually with UnityEvents just doesnt cut it for me

steady bobcat
#

you can sub in code too but yea a c# event is preferred for code only stuff

tawny elkBOT
stuck hatch
#

Hello I'm working on VR game and encounter problem when I want to attach and detach object to another game object. When I detach game object (grab) the size will be smaller. does anyone know how to solve it?

#
public class OnCollisionTrash : MonoBehaviour
{
    public Transform slotObject;
    public GameObject attachedTrash;
    private bool isAttached = false;

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Trash") && !isAttached)
        {
            // Attach trash to slot
            other.transform.SetParent(slotObject, true);
            other.transform.position = slotObject.position;

            // Optional: Stop movement
            Rigidbody rb = other.GetComponent<Rigidbody>();
            if (rb != null)
            {
                rb.velocity = Vector3.zero;
                rb.angularVelocity = Vector3.zero;
                rb.isKinematic = true;
            }

            attachedTrash = other.gameObject;
            isAttached = true;
        }
    }

    public void DetachTrash(GameObject trashObject)
    {
        if (attachedTrash == trashObject)
        {
            // Detach from slot
            trashObject.transform.SetParent(null);

            Rigidbody rb = trashObject.GetComponent<Rigidbody>();
            if (rb != null)
            {
                rb.isKinematic = false;
            }

            isAttached = false;
            attachedTrash = null;
        }
    }
}
leaden ice
copper inlet
wary ferry
#

Is there any built in file picker in unity that isnโ€™t the editor utility one?

hexed pecan
wary ferry
#

Huh wild I really thought their would be something built in for that

#

Thanks for the answer!

steady bobcat
#

but in editor they know its gonna be one of 3 platforms so its easier to use the os provided one

wary ferry
wary ferry
delicate flax
# wary ferry This looks great Iโ€™ll probably go with using this

just so you know, there is a bug in that lib during builds (from unity 2023.3+ iirc)
https://github.com/gkngkc/UnityStandaloneFileBrowser/issues/145
the fix is posted in the issues tab on the github

GitHub

I was building my Unity game for IL2CPP on Windows, when I got this error: Mono.Linker.LinkerFatalErrorException: ILLink: error IL1005: System.Windows.Forms.XplatUIX11.SetDisplay(IntPtr): Error pro...

wary ferry
#

Thanks for the heads up

woeful mango
#

Hi, is anyone familiar with making particle system with collision on? my cubic smoke kept clip through floors, it sometimes work and sometimes don't. I want to do a rocket landing smoke effect.

#

I did add rigidbody to my terrain tiles. Sometimes the particles worked some times it doesn't like in the video. Two of them worked but other two didn't. There are times that they all worked.

#

here are my particle collision settings. Not sure more information is needed.

#

Thanks

hexed oak
#

I'm trying to use EditorSceneManager.GetSceneByName to get the scene name while in editor. It works for one scene but not another.

I have 2 scenes, PrimaryScene and SecondaryScene.
PrimaryScene works when using that call, but SecondaryScene fails. They're both in the same directory

somber tapir
hexed oak
#

yes

#

index 0 and 1

#

Though that may change between projects, it's not guaranteed

steady bobcat
#

you can search for the asset by name btw

hexed oak
#

oh my god EditorSceneManager only returns information if the scene is loaded in the hierarchy

#

that is so stupid, the whole point of using it is to get the scene name so I can load it into the hierarchy

steady bobcat
#

so search for the asset and load it then with the editor scene manager

#

AssetDatabase.FindAssets("t:Scene MyCoolScene");

hexed oak
#

yeah that's gonna have to be how I do it

wild elbow
#

Are script-only stack traces supposed to work when logging in non-development builds? Up until recently I swear they did and were just missing line numbers. But now it's just the log message and no stack. I don't see any relevant changes in our project's code or packages, I've looked at all the build and player settings, I'm checking Application.Get/SetStackTraceLogType() at runtime. And it all looks fine. If I turn on full stacks, it works, but script-only just fails. What am I doing wrong? (Unity 2022.3.42f1, mono scripting back end, Windows build)

steady bobcat
neat tundra
#

so I'm really not sure what the heck is going on

wild elbow
hexed oak
# steady bobcat ``AssetDatabase.FindAssets("t:Scene MyCoolScene");``

As it turns out, in other projects, I have scenes that are named PrimaryScene1, SecondaryScene3, SecondaryScene4, etc.

I have the correct name of the scene that I need defined in a scriptable object, but using AssetDatabase.FindAssets($"t:Scene {mySceneName}"); causes it to return the wrong scene--basically a total crapshoot if it finds the one I want or not.

steady bobcat
hexed oak
#

yeah actually, I'll just iterate them to match the string name I have. FindAssets returns an array of guids. Gotta get the actual asset

steady bobcat
#

yea you can convert guid to asset path and then load with this

hexed oak
#

yep, got it working! Thank you!

gilded jackal
#

Hi im having issues here but the scenes are in the build settings?

steady bobcat
gilded jackal
steady bobcat
#

the error states the scene name you used and this doesn't match any of the ones in the build settings list

gilded jackal
#

but here are them together

#

U see there both titled LoadingScene

steady bobcat
#

read it again and think ๐Ÿ˜

gilded jackal
#

Oh so my script has it as loadingscreen but its mismatches everywhereelse?

#

Ahh i get it thanks im dumb dumb

fiery steeple
#

Hey, I have these areas that I need the player and NPCs to be at certain time and if they're not in those areas at certain time they will receive a strike and after 3 strikes they're punished. So what's the proper way to communicate from the script that's on those areas (Box Collider with "Trigger" set to true) to the DailyRoutineManager that handles all aspect of checking if they were in those areas at the right time, punishing them, etc... ?

right now I have this :

  • DayNightCycle.cs handles the DayNight timer of 24 hours and it has an Action called OnGameTimeChanged that's called everytime the time changes
  • DailyRoutineManager.cs that subscribes to OnGameTimeChanged to do all the checking about the players and NPCs
  • OnAreaEnter.cs that's on those BoxCollision ( Trigger) that detects when those players or NPCS enter those overlap box

So I need to connect them in some way to make all this system work

rigid island
low violet
#

what design patterns do you guys think are the most useful and least useful just in general

fiery steeple
rigid island
#

They're all useful for the most part..
some tops, observer, singleton , factory , command etc.
least .. don't overuse / abuse singletons

chilly surge
#

The most useful design patterns are the ones that fit the problems you need to solve.

ripe blade
#

Can anybody tell me why when i use netcode for gameobjects both of the players move with only 1 players input.

maiden trellis
#

how to make some sort of paint decals?

#

like big droplet of paint leaving a splatter on wall

maiden trellis
#

how to make a splatter of paint like a gel in portal 2

#

i think tht projectors will make fps go 0

steady bobcat
maiden trellis
maiden trellis
#

no projector

#

because they are expensive

steady bobcat
#

then you can research about the other thing I said

maiden trellis
#

how to fix this

near granite
#

hi, im kinda new to unity hope u guys can tolerate e for asking a lot of questions

safe flame
hexed pecan
maiden trellis
hexed pecan
#

Show its settings

#

And material

maiden trellis
trim schooner
#

and this is a code channel, if it's not code related...

near granite
#

does anyone know whats the meaning behind these codes

#

i can build apk for a while now, but suddenly it has an error when i tried building em

#

i think my last progress is when i tried to add firebase auth,firestore and database package to unity

vestal arch
near granite
#

sure

trim schooner
#

They're in packages.

If you're not using those packages, remove them. If you are, remove them then add them again.

near granite
#
  1. Packages\com.unity.addressables@1d7f6a740e58\Runtime\ResourceManager\AsyncOperations\AsyncOperationBase.cs(39,32): error CS0433: The type 'Task<T>' exists in both 'Unity.Tasks, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'

  2. Packages\com.unity.addressables@1d7f6a740e58\Runtime\ResourceManager\AsyncOperations\AsyncOperationBase.cs(39,32): error CS0433: The type 'Task<T>' exists in both 'Unity.Tasks, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'

  3. Library\PackageCache\com.unity.inputsystem@e2c83221d2dc\InputSystem\Actions\InputBindingComposite.cs(221,46): error CS0121: The call is ambiguous between the following methods or properties: 'System.MissingExtensions.GetCustomAttribute<T>(System.Reflection.MemberInfo)' and 'System.Reflection.CustomAttributeExtensions.GetCustomAttribute<T>(System.Reflection.MemberInfo)'

  4. Library\PackageCache\com.unity.inputsystem@e2c83221d2dc\InputSystem\Controls\InputControlLayout.cs(1180,51): error CS0121: The call is ambiguous between the following methods or properties: 'System.MissingExtensions.GetCustomAttribute<T>(System.Reflection.MemberInfo, bool)' and 'System.Reflection.CustomAttributeExtensions.GetCustomAttribute<T>(System.Reflection.MemberInfo, bool)'

  5. Library\PackageCache\com.unity.inputsystem@e2c83221d2dc\InputSystem\Actions\IInputInteraction.cs(326,56): error CS0121: The call is ambiguous between the following methods or properties: 'System.MissingExtensions.GetCustomAttribute<T>(System.Reflection.MemberInfo)' and 'System.Reflection.CustomAttributeExtensions.GetCustomAttribute<T>(System.Reflection.MemberInfo

#

there's a total of 15 errors but most of them are same errors

steady bobcat
#

Do you have a Unity.Tasks dll in the project?

#

some old plugins included this

near granite
#

pretty sure not

steady bobcat
#

use the search box then and find out

near granite
#

let me check it again to make sure

steady bobcat
#

I think firebase used to include it in old versions

near granite
#

yea pretty sure not there

near granite
steady bobcat
#

no search in the project window...

#

for a file

steady bobcat
near granite
#

Ouh

#

Yea it's there

#

Only one tho

steady bobcat
#

delete and see if everything is fine. I dont even remember where they came from they just exist in our projects and get carried forward in the base ๐Ÿ˜†

near granite
#

I tried removing them multiple times but still there

steady bobcat
#

you can search with explorer in Library\PackageCache

near granite
steady bobcat
#

yea if thats what caused the errors to show last time

near granite
#

Yea pretty sure not removing unity.task

#

Ouh

#

Okay so it reduced the error to 8 now

#

Actually 6

#

Cause the other two are just compiler errors

#

I only left with inputbindingcomposite.cs and inputcontrollerlayout.cs

slim pelican
#

what is the best way to implement anti corner-snagging? I've tried using a (yellow) vertical raycast in front of the player (slightly behind the actual horizontal raycasts) and it works surprisingly well but I was wondering if this is a known method that has any downsides to it, or if theres a much better method

(also please ignore the blue raycasts, those arent the horiziontal collision raycasts)

trim schooner
near granite
#

Yea I tried

naive swallow
slim pelican
slim pelican
slim pelican
naive swallow
#

It's partially a joke, but also don't be afraid to just spam raycasts everywhere, they're incredibly cheap

novel cypress
#

Hello, I would like to know th best practice to manage multiple managers. For example, let's say I have Level Manager, Inventory Manager and Game Manager in my Level scene. When the player will go back to the Menu scene, all these Managers will be useless, and they could even break the game since some references (like player for example) won't be found. So, what is the best way to tell which managers I need and in which scenes ?

naive swallow
fleet bison
#

can you not call a method from a generic interface from an action like this?

#

from any other source "damageable.TakeDamage()" works just fine, but calling it when this action is ran doesn't work

tawny elkBOT
fleet bison
rigid island
#

just fyi its hard to see code as an image especially on mobile..

fossil obsidian
#

i want a working PC in my game, and idk what would be the best way to organize and instantiate new files. SO? Normal classes? Someone give me some orientation

robust dome
#

depends on what you want to do

rigid island
fleet bison
fossil obsidian
#

and u can also create new files, rename, etc

rigid island
#

yes I understood the computer part, but what do you want to do with the files is more important to know

#

what do these files do?

fossil obsidian
#

depends of the type

rigid island
#

SOs and POCOs are very similiar, so that goes also with the itdepends

fossil obsidian
#

you have documents, audio, video, etc

rigid island
#

I would probably use POCOs unless I have a specific reason to use SOs

fossil obsidian
#

what's POCO?

rigid island
#

Plain C# object

#

like class / struct

#

(Non-monobehaviour)

fossil obsidian
#

oh normal classes

fleet bison
#

the way id do it is have a generic "file" interface that supports being opened/closed or whatever you'd need, then have each unique file type implement it's own behavior, but that's having never really used SOs

high oracle
#

hey guys i have a quick question for you i'm begginer with unity and i want know wath langage i need tu use

rigid island
high oracle
naive swallow
rigid island
#

thats from the official website

#

can't be any more legit / official than than a random on the internet ๐Ÿ˜› I could've been lying

high oracle
#

true

slim pelican
#

Interesting.

leaden ice
slim pelican
#

Why do some people prefer doing simple raycasts over using a boxcast sometimes then if it does the job better (seemingly)

leaden ice
#

different tools for different purposes

#

if you want to cast a ray through the scene, use raycast
If you want to cast a box through the scene, use boxcast

slim pelican
#

Sorry I meant specifically for collisions

leaden ice
#

what about them

slim pelican
# leaden ice what about them

I've seen many people use simple line raycasts for kinematic collision detection so I'm unsure why they'd chose to do that over a boxocast

leaden ice
slim pelican
#

Fair enough lol

leaden ice
slim pelican
#

I've done all of my collisions and movement features (auto stepping) with raycasts on a boxcollider ๐Ÿ˜ญ

#

Works fine except when walking into vertices or walking along a vertex (the player bobs up and down because the corner can go between the vertical collision raycasts

trim schooner
lilac frigate
#

Does anyone know of any good up to date examples of server authoritative movement with client prediction and reconciliation

rigid island
fiery steeple
#

Hey,
are there advantages / drawbacks to use tag over component / script + TryGetComponent() and vice versa please ?

vestal arch
fiery steeple
vestal arch
#

if you're using this for static references, you should use serialized references instead

fiery steeple
vestal arch
vestal arch
fiery steeple
vestal arch
#

that doesn't change the fact that they're magic strings though

#

if you rename a tag it also breaks

fiery steeple
#

oh yeah, so it's better to use Components and TryGetComponent<>() ?

somber nacelle
somber nacelle
#

lol yeah i could tell based on the fact that you have tags in your intellisense

vestal arch
#

but tags aren't really comparable to getcomponent calls anyways, so not sure what you're really asking

somber nacelle
#

if the options are compare tag vs trygetcomponent it sounds like this is likely for collisions rather than having direct references

vestal arch
#

tags give you gameobjects, getcomponent gives you components

fiery steeple
# vestal arch it's better to used serialized references if possible

Can't always do that. Here for instance I have an area that I need to check what entered it and if it's a Player or an NPC execute some code, so I could give both the same tag but it doesn't look like the best way as if I need those to have other tags I can't do that anymore, so that's why I thought about giving them a script component called "Entity" and check the thing entering the area if it has that script.

somber nacelle
#

but TryGetComponent is typically going to be better if you're going to need to get the component. if you're not then a CompareTag is just fine and you can make it ever so slightly better by using a TagHandle rather than passing the string directly to the method

fiery steeple
fiery steeple
steady bobcat
#

then i guess you get the component and read the id from that

brisk axle
#

hey there, quick question:

I do have a script AbilitySystem that has a list of abilities ([SerializeField] private List<Ability> abilities;). my Ability is an abstract class (inheriting from ScriptableObject) that defines some basic things for abilities. I want to have abilities like Dash that simply inherit from Ability - but I'm unable to drag&drop the Dash ability into my ability list of my AbilitySystem. what am I missing here?

night harness
mossy snow
#

probably trying to drag the script instead of an SO asset

opaque vortex
#

can I use perlin noise and fft transforms in the burst job system or no?

#

I am trying to move my perlin noise generator to a burst compiler to increase performance but is this even possible?

shell scarab
#

Hey, can anyone help with displaying an animation for a calculated random outcome? Doesnโ€™t have to be an actual animation, could be animated with code.

For example a dice roll, it would be calculated but then needs to be animated to show the dice land on that number.

Or another example spin the wheel type thing, where the number chosen is calculated but it needs to land on the right number visually.

Km not sure where to start with this, and i cant find anything at all through googling, although im not sure exactly what to google for this.

cosmic rain
shell scarab
#

not sure how itโ€™s faked

cosmic rain
#

There could be many ways. For example, with the dices, there could be only one or several animations, and they know what side they would end up falling on, so they set the initial rotation or the assigned textures such that the desired outcome is displayed.

cold parrot
shell scarab
#

im still not exactly sure how this helps and i feel its missing a ton of context. Can you explain in what way this dice roll effect would be shown to the player? And i think this quickly gets more complicated if there are multiple dice.

night harness
#

if the random outcome is calculated, generally displaying said outcome is "calculated". a majority of games do not pre-calculate random outcomes then dynamically handle displaying them (in this case the physics of a dice rolling)

cosmic rain
shell scarab
#

So for a set of 4 dice iโ€™d have 1,296 animations?

#

that doesnt seem practical

cosmic rain
#

No. You only need 1 animation

night harness
#

no you'd have 6 animations that can be played on 1 dice 4 times

cosmic rain
#

You seem to be missing the point

shell scarab
#

I see what youโ€™re saying now

#

One animation, and just place the faces on the sides so that the one you want ends up on top

#

Is that what youโ€™re saying?

cosmic rain
#

Yes

last raven
#

is there any way in unity to make [CallerFilePath] use relative paths instead of absolute? I know how to do that in .NET but I have no idea how to do that in unity

last raven
#

I found a way by adding -pathmap:PATH=. but now I have the problem that I have to hardcode PATH, I don't know how to use environment/project variables in csc.rsp file

#

I tried -pathmap:$(MSBuildThisFileDirectory)=. and -pathmap:$(SolutionDir)=. but neither work

#

is it possible to add C# compiler options in editor scripts before build?

vapid swift
#

hi

#

Can someone tell me why despite having using Unity.Services.Multiplayer; in my code

#

Lobby can't be resolved?

#
Assets\Scripts\MainMenuHandler.cs(10,13): error CS0246: The type or namespace name 'Lobby' could not be found (are you missing a using directive or an assembly reference?)
#

thanks in advance

last raven
#

because using only dumps names in the namespace into file global scope so you don't have to type fully qualified name but it does not actually add any references to project/assembly/package

#

make sure that package containing that class is actually added to project

vapid swift
#

yeah

vapid swift
#

I mean I installed it from the Package Manager

last raven
#

look if you need to maybe add assembly reference manually with -r:assemblyname parameter csc.rsp file or into asmdef file if your code is in the library

vapid swift
#

i don't even know what this assembly stuff is ๐Ÿ˜ญ

night harness
#

is that class even in that package

#

can you link the api reference for it

night harness
#

what version of unity are you on

vapid swift
#

6.0

#

i dont have any asmdef files

somber nacelle
#

Does that package even include a type called Lobby?

vapid swift
#

From what I know it should

somber nacelle
#

Hint: look in the documentation

last raven
#

you don't but packages usually have, but unity ones should all be set to "auto referenced" so you don't have to do anything else usually and yes, you're right, based on documentation it should have Lobby class but it's in the Unity.Services.Lobbies.Models

vapid swift
#

Well I don't really understand the documentation

#

Which is why I'm asking here

vapid swift
#

it says "Lobby" is in the Multiplayer Services SDK

last raven
#

doc is pretty garbage like all unity docs

somber nacelle
#

Is your IDE configured so you see red underlines for errors in your code?

last raven
#

so try using Unity.Services.Lobbies.Models.Lobby instead

vapid swift
#

thank you very much, I'll try that

somber nacelle
#

Instead, since the namespaces have been changed in the latest version, they should use the quick actions in their IDE to add the correct namespace

vapid swift
#

I got the C# and Unity Extensions for VSCode, nothing is turning red when somethings wrong

last raven
#

it should work

#

you might need to configure it

#

I use it and it works for me

vapid swift
#

damn

last raven
#

make sure unity also has VSCode extension, VSCode is selected as editor and you use "regenerate .csproj"

#

that might help

vapid swift
#

well now im getting totally different errors

#

but that should be due to the Lobby finally getting recognized

#

thank you very much guys! ๐Ÿ™‚

last raven
#

if you correctly configure VSCode you can fix that with Ctrl+. on these classes

#

also if you want to use C# 10 in unity you can also do that

somber nacelle
last raven
#

is it possible to use environment variables in csc.rsp file?

vague cosmos
#

Hi there, i was experimenting with using input system to make a local multiplayer game, but using the player input component and player input manager, i can only join with the keyboard, and my controller (Xbox series controller) does not work. I checked in the input debugger, and the controller is being detected, so i'm kinda at a loss

#

Here are the related screenshots

leaden ice
quick elbow
#

Why use IL2CPP vs. Mono? I see that generally IL2CPP offers better performance. I imagine that is still true since it's AOT compilation. However, I also see IL2CPP can introduce a lot of weird errors

leaden ice
quick elbow
leaden ice
#

I find that IL2CPP issues are quire rare and usually isolated to reflection-based stuff.

quick elbow
#

Good to know. My prior projects were for Universal Windows Platform... which doesn't really get much support. So I imagine that was a part of our problem

leaden ice
#

probably yes

tepid shore
#

somehow this script makes my fps go from over 280 to barely 90

violet nymph
tepid shore
#

probably some wierd issue with the unity editor playmode

violet nymph
#

Serialization causing lag is weird

tepid shore
#

yeah

#

turning it to private fixed the issue

south summit
#

is there a #support here? Because i need some help

young tapir
#

With?

vestal arch
#

why are you using unity 2017 lol

violet nymph
#

Definitely not code related

south summit
cold parrot
steady bobcat
#

Remember that person who was using unity 5

#

Best to keep up with the oldest version with support which is 2022 rn (2021 I think has extended pro support)

vapid swift
#

Can someone tell me what it means if you get this error, despite having set all dependencies (dragging the Button Component into the Button Field of the Canvas > MainMenuHandler Script in this case) ?

Initialization error: Object reference not set to an instance of an object
UnityEngine.Debug:LogError (object)
MainMenuHandler/<Start>d__7:MoveNext () (at Assets/Scripts/MainMenuHandler.cs:84)
System.Runtime.CompilerServices.AsyncVoidMethodBuilder:Start<MainMenuHandler/<Start>d__7> (MainMenuHandler/<Start>d__7&)
MainMenuHandler:Start ()
vestal arch
#

perhaps something was unassigned at runtime

vapid swift
#

Debug.LogError("Initialization error: " + e.Message);

vestal arch
#

or maybe you're looking at the wrong component

vestal arch
vapid swift
#

I just catch an exception there and log that

#

here's what I do that throws the error:
playButton.interactable = true;

#

I just access the button and set interactable to true

vestal arch
#

add gameObject to the log as the second argument, so you can see which object it's logging from

#

it might not be the one you're looking at in the inspector

vapid swift
#

ohh okay

dense rock
#

I have some weird problem where I use

Destroy(gameObject, 5f);
```Now if the 5s aren't up when I exit the play mode, the object is apparently saved in the scene. Is there a reason for that? context might be important, it's instantiated as child of a dontDestroyOnLoad object
vapid swift
#
Initialization error: Object reference not set to an instance of an object
UnityEngine.Debug:LogError (object,UnityEngine.Object)
MainMenuHandler/<Start>d__7:MoveNext () (at Assets/Scripts/MainMenuHandler.cs:84)
System.Runtime.CompilerServices.AsyncVoidMethodBuilder:Start<MainMenuHandler/<Start>d__7> (MainMenuHandler/<Start>d__7&)
MainMenuHandler:Start ()

Now it logs this

#

the exact same as before???

vestal arch
#

click (or double click? i forget) the error to highlight what object it's from

vapid swift
#

it's Canvas as I thought

civic girder
#

In a game where the UI is part of the gameplay (like pokemon, FF, etc).

What type of class is responsible for controlling the UI?

Like would the battle system be calling the UIManager?
Or the turn system calling the UI?
Or others?

vestal arch
latent latch
vapid swift
#

XD

#
try
        {
            await AuthManager.Instance.InitializeAsync();
            isInitialized = true;

            // Slight delay to ensure UI updates
            await Task.Delay(100);

            playButton.interactable = true; // Enable the Play button after initialization
            if (statusText != null) statusText.text = "Ready! Click Play to join.";
        }
        catch (System.Exception e)
        {
            if (statusText != null) statusText.text = "Initialization failed: " + e.Message;
            Debug.LogError("Initialization error: " + e.Message, gameObject);
        }
#

that's the entire try catch block

vestal arch
#

try narrowing it down then

#

or could just comment out the try/catch bits so it points to where the error actually comes from

vapid swift
#

yeah so i let it log itself

#

just throw the exception

#

I'll try that

#

ohhhh

#

now it makes more sense

#
NullReferenceException: Object reference not set to an instance of an object
MainMenuHandler.Start () (at Assets/Scripts/MainMenuHandler.cs:72)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) (at <314938d17f3848e8ac683e11b27f62ee>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <1e74f08236fb4c1791a523c0bf197e6c>:0)
UnityEngine.UnitySynchronizationContext.Exec () (at <1e74f08236fb4c1791a523c0bf197e6c>:0)
UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <1e74f08236fb4c1791a523c0bf197e6c>:0)
#

Line 72: await AuthManager.Instance.InitializeAsync();

civic girder
vestal arch
latent latch
#

So, if you do want callbacks from the CombatManager, a bi-directional reference can suffice

civic girder
latent latch
# civic girder Yeah I meant as events. I just mean like: instead of each action doing an event ...

UIManager -> Invokes event for what the user has selected -> delegates to a method inside of CombatManager (for example the player pressed Attack)
UIManager however may also need callbacks for say stuff like updating statistics like health and game state related information, so it'll also have to subscribe to those methods on the CombatManager.

This would require some reference to bind those events, but otherwise you can also make a event bus that acts as the inbetween (proxy)

wicked scroll
brisk axle
#

if creating an instance of these abilities is the only way to achieve that; is there an alterantive? having multiple Dashes seems counter productive

wicked scroll
#

you would only create one

#

there's lots of alternatives

brisk axle
#

okay, let's ask differently: would this approach be any kind of bad practice?

wicked scroll
#

not necessarily, plenty of folks go that route

#

like anything, it depends on what you're trying to accomplish

brisk axle
#

since a lot of ppl talk about scriptable objects as data containers it seems a bit weird since I'd like to implement the logic of how an ability works also in that class

#

would that be possible or even wrong?

brisk axle
wicked scroll
#

it can work, you just end up having to pass a lot of things into those method calls or some kind of larger context

wicked scroll
brisk axle
#

true ๐Ÿคทโ€โ™‚๏ธ ๐Ÿ˜„

wicked scroll
#

this architecture is essentially commands/actions with some weird indirection in exchange for being easily editor configurable

#

whether that tradeoff is worth it will be up to you

brisk axle
#

ok thanks

steady moat
astral sky
#

I'm getting hundreds of these messages about the font and they're flooding my logs making them unreadable
I have "Include Font Data" toggled, I do not understand

steady moat
astral sky
#

Collapse helps in the editor but not in the player.log

steady moat
#

If you are inspecting the log manually, you can use a tool to do a search and replace.

#

Notepad++ and regex can probably works.

astral sky
#

I really don't want to be replacing 900k of lines every time I run the test runner

#

actually 16k, but point stands, I want to fix this, not ignore it

sonic trench
#

In basic terms,

#

oops wait

#

In basic terms,
If I have a rigidbody2D, and on the Update() function i have an 'if (Input.GetKeyDown(x))' {PerformJump()},
is there a way to call the function only on the next FixedUpdate() frame? is it worth the effort?

vestal arch
sonic trench
vestal arch
#

i mean, "performjump" is pretty self-explanatory

#

but if there's more stuff that does rely on being on fixedupdate, then it's not too hard to do

#

just queue it up and consume that in the fixedupdate

sonic trench
#

So if I wanted to do a timed-jump mechanic, like with short jumps and high jumps based on the time holding the key, should that be done in fixed update?

vestal arch
#

could be a bool if it should only be called once, could be an int if it could be called multiple times (if the key was pressed multiple times in that 0.02s gap), could be a list/queue of actions to handle multiple functions with the same behavior

vestal arch
sonic trench
#

Making it too complicated in my head

vestal arch
#

there's a lot of ways to do that system, it might be split up over update/fixedupdate

sonic trench
#

doesn't seem unreasonable for unity to be able to queue something like that internally, but I'm using a dated version anyway lmao

vestal arch
#

input is frame-bound, they update on frames only

#

GetKeyDown is true for the 1 frame it was pressed on
if FixedUpdate happens to miss that frame, too bad

#

it's just not logically correct

somber wyvern
#

HI! I am trying to import a shared library I have written into unity, but I am having some trouble. On import, I get the following error:

"TypeCache is unable to load info on field .FindServerForPlayerResponse::<FoundServer>k__BackingField. Are you missing a reference?"

Basically saying that its having trouble with a backing field for one of the values. However, the way that I have the shared lib written shouldnt really have any issues, the field it refers to is just a bool, and when I try to remove it, it just says that the issue was found with the next variable I had defined there, so I am just assuming its an overall issue with the DLL, which googling seems to conform

The library is only a few files that have response/request packet data, an example is as follows:

using Network.Attributes;
using Network.Packets;

[PacketRequest(typeof(FindServerForPlayerRequest))]
public class FindServerForPlayerResponse : ResponsePacket
{
    public FindServerForPlayerResponse(bool foundServer, int serverId, string name, string publicIpAddress, int port, FindServerForPlayerRequest request) : base(request)
    {
        FoundServer = foundServer;
        ServerId = serverId;
        Name = name;
        PublicIpAddress = publicIpAddress;
        Port = port;
    }

    public bool FoundServer { get; set; } = false;
    public int ServerId { get; set; } = 0;
    public string Name { get; set; } = "";
    public string PublicIpAddress { get; set; } = "";
    public int Port { get; set; } = 0;
}

Ive tried changing the framework it targets, ive tried changing unity to target the .net framwork or .net core in the player settings but nothing clicks

#

If anyone has dealt with a similar issue, please let me know if you know how to solve this sort of thing

leaden ice
somber wyvern
#

Yes I have a few other projectrs that reference the project in my solution and use the class

#

It compiles and works just fine in the normal vs/C# context but just has trouble when brought into unity

somber wyvern
#

Update: Found it! I needed to manually type that the target was dotnet standard 2.1 in the actual csproj file and unity finally accepted it

#

Thanks for help regardless :D

sonic trench
#

I know this isnt really a unity (or even coding) question, but is there a way to turn off these spaces in visual studio?

steady moat
sonic trench
vestal arch
vestal arch
#

might wanna remove those embeds

#

also might wanna remove all that metadata

sonic trench
sonic trench
vestal arch
#

the other guy, absolute wall of embeds lol

sonic trench
#

trueee

#

cant tell if they trying to be helpful or if it was passive aggressive lmao

fast glade
#

found some really confusing and inconsistent code, i set a class in my mono behaviour that's supposed to be null at the start of the game(which i supposedly achieve by putting class = null at the start function). But for some reason it doesnt work sometimes

steady bobcat
fast glade
steady bobcat
#

!code

tawny elkBOT
naive swallow
steady bobcat
#

i presume they meant a field but tru

fast glade
#

also would putting [NonSerialized] help my case?

steady bobcat
#

yes but share the code...

naive swallow
fast glade
steady bobcat
#

what was the field type then?

fast glade
#

it was [HideInInspector] before

#

i did some research

steady bobcat
#

yea that doesn't stop serialization

fast glade
#

and with the HII attribute it just gives it a default value anyways :p

#

while nonserialized automatically sets it as a null from the beginning

steady bobcat
#

yea any serialized field gets given a value (e.g a List will not be null as unity will give it a value)

fast glade
steady bobcat
#

what i dont understand is WHAT IS THE TYPE

fast glade
#

and the class type is serializable so that i could other instances of it on the inspector

steady bobcat
#

without using this, a class field cannot store null via unity serialization

steady bobcat
#

I presume the inspector overrode the value to not be null due to it being SerializeField

#

in a build it should act differently

#

Otherwise use a custom inspector to draw this information

fast glade
steady bobcat
#

no its due to this quirk with unity serialization and only this situation shows this behaviour
anywhere else the class acts like we expect

fast glade
steady bobcat
#

the serialize ref doc page explains how it allows storing sub types and null

fast glade
#

ty for that again

steady bobcat
#

from the page:

// This field must use serialize reference so that serialization can store
        // a reference to another Node object, or null.  By-value
        // can never properly represent this sort of self-referencing structure.
        [SerializeReference]
        public Node m_Next = null;
woeful hamlet
#

I'm making a rotating tiles puzzle, as in, there's a grid of stationary square tiles (GameObjects, not Tilemap tiles) depicting various pipe segments, and you have to click and rotate all of them to make the pipes connect from one side to the other.

#

The visual part was easy, but now I'm wondering if my idea for checking the connections is too complicated because I'm missing some convenient Unity feature.
My thought is for each Tile to have a list of Directions (as an Enum) its pipes are pointing, and references to its neighbours, so whenever it rotates, it can poll its neighbours which Directions they're pointing, and there's a left/right or up/down match between them, save that Direction(s) in a 'connection' list, then tell all its neighbours to update.
And when checking the connection (at the end, not dynamically on every update), I'd start from the entrance tile and recursively find its furthest connection by asking all neighbours for their furthest connection, until I get back a bunch of Null for dead ends, or the exit tile.
I'm aware this description is kinda rough and inaccurate, but it's not about the implementation yet, but the general idea. Am I missing some Unity/C# feature that would make a lot of that work redundant, or am I generally on the right track?

unkempt meadow
#

Guys, is there anything better than a character controller if I don't want all the forces from a rigidbody?

I don't trust my own hardcoded collision. Is there really not anything else?

steady bobcat
vestal arch
#

you can disable gravity and linear damping if you want

unkempt meadow
vestal arch
#

yeah what do you mean by "all the forces"

#

you can disable the built-in forces and you could just not AddForce if you don't want to

#

what's the issue with a rigidbody

unkempt meadow
#

it fucks around a lot

#

which a char controller doesn't do

#

but char controller has some limitations that make it unviable to me

#

and with a kinematic rb without gravity, I thought moverotation would check collisions while rotating but it doesn't

vestal arch
#

or what

unkempt meadow
#

wym

#

yea?

vestal arch
#

then you're using it wrong yeah

unkempt meadow
#

oh no sorry

vestal arch
#

rigidbody controls transform

unkempt meadow
#

no I used moverotation

#

move position sorry

#

or the other one