#💻┃code-beginner

1 messages · Page 834 of 1

verbal dome
#

It's safer to start the ray from inside the collider

stuck parrot
#

sorry raycasts are new to me, first time using them

rich adder
#

tbh I rather make a gameobject as the origin at the feet

#

or my player object is usually at the feet anyway, and just make my collider center at offset

verbal dome
#

Or use an empty gameobject's position

naive pawn
#

wouldn't the typical approach be to exclude the player's layer from the cast

rich adder
#

that too

verbal dome
#

It's very common to just start the cast from inside the collider

#

You are also assuming that the player has a unique layer etc.

chrome apex
#

I'm just not quite how to do it. The methods that I've tried rotate the map when I look up or down or just generally don't match the rotation. What would you do?

verbal dome
#

Rays can't hit the inside of a collider except for a meshcollider if you have a certain setting on

rich adder
#

I do it this way.. much easier and never worrying about sizing the player changing the offset from center

naive pawn
limpid stratus
verbal dome
#

A screenshot of the in-game map would probably help us understand better

chrome apex
naive pawn
chrome apex
chrome apex
naive pawn
#

just pitching up/down? and turning on Y doesn't affect it?

#

that doesn't sound right from your original description

#

the constraints/behavior here are not very well defined

limpid stratus
chrome apex
naive pawn
#

that is the implementation

#

we still barely understand the design

verbal dome
naive pawn
#

you said the player can be oriented in any way - is that actually true? can the player rotate on Z?

verbal dome
#

X doesnt make sense to me, unless this is Hill Climb Racing (and that would probably be Z in 2D anyway)

chrome apex
naive pawn
#

ok so does X rotation actually matter then?

limpid stratus
#

Can you take a screenshot of your player with the map pulled out? @chrome apex

chrome apex
#

i.e. when I look up or down, my map rotates

verbal dome
#

Probably faulty code/math then

#

You need to show something

naive pawn
chrome apex
#

if you want to see its transform gizmos etc. I can go in and screenshot

naive pawn
#

you said the player can orient "in any way", but it's not clear what this actually entails.

can the player rotate on Z?
can the player rotate beyond ±90° in pitch?

limpid stratus
#

that would be helpful. It is 99.99% a very simple transformation matrix issue, but we can very well mislead you without more context

chrome apex
naive pawn
#

ok then no issue with just mapping the Y to the map's orientation then, and you already said you don't want X to matter

#

design handled. only now does it make sense to move to issues in implementation

chrome apex
naive pawn
#

the "orient in any way" was very vague yeah

verbal dome
#

In a thread some days ago you said this is for a navigator screen in a racing game, that's the context I have

naive pawn
#

they mentioned diving thonk

verbal dome
limpid stratus
#

I don't understand any of it. is it a projecting 3D positions onto a plane? Is it rendering them in 3D like in sci-fi movies? What defines the transformations of the tablet related to the player?

chrome apex
verbal dome
chrome apex
#

lmao

verbal dome
#

I was like "why would X matter" lmao

chrome apex
#

were you wondering why I would have 3d movement in a racing game?

naive pawn
verbal dome
#

The pitch/x axis stuff confused me yeah

naive pawn
limpid stratus
#

My understanding is that you want to render a top-down projection of the navigated path onto the tablet. Is that assumption correct?

chrome apex
# naive pawn to check my understanding - it's projected from 3d to 2d by discarding Y, right?

Well, kinda.

So the way this works is it's not an an actual canvas, it's a real world object. Initially I set the y to the same calue for all points but I changed it by adding a very slight offset scaled down a lot from the real world y value

The purpose of that is I wanted to keep some hright data do I can shade the line renderer in such a way that it can show which lines go downward and which lines go upward but that's irrelevant to this discussion

naive pawn
#

can you not just grab the Y rotation from the player and apply it to the map?

chrome apex
limpid stratus
#

You'd make your line renderer local, you'd make "up" point towards the tablet's surface, forward point towards the top part of the tablet

#

definitely a clipping pass, and probably offset local y based on the lowest point traveled * your height scalar

naive pawn
#

i think the GO setup is more pertinent though, you gotta make sure the map has its own local space that can rotate like that properly

chrome apex
short gust
#

what is the "recommended" way of auto-populating serialized fields in general (like pre-bake references to other components if they exist on a gameobject, etc.)?
OnValidate is kinda meh, Reset requires using reset option button on component itself (so it's kinda still manual), [ExecuteInXXX] attributes are kinda "risky" and require a lot of boilerplate/conditional compilations or writing code in specific way to prevent bloat/bugs in runtime. is doing that in some simple custom inspector script and inherit from it where I need this stuff - good idea or it's bad no matter what I do, lol?

naive pawn
chrome apex
#

but when I look up or down, the map rotates around. I tried mapping to different axes, assuming I might have confused myself somewhere but it just doesn't align itself correctly

#

it basically rotates itself wherever it wants

naive pawn
chrome apex
#

Maybe I'm confusing the line renderer somehow by rotating it?

Cause the mapping itself works

naive pawn
#

make sure it's not actually rotation.y, that'd be a quaternion value

limpid stratus
#

furthermore, make sure you are using local rotation

chrome apex
limpid stratus
#

it needs to rotate locally

chrome apex
#

yea yea, I meant to say tablet's local y

naive pawn
#

"player's world axis" isn't really a thing, do you mean an axis in the player's local space

chrome apex
naive pawn
#

should probably just show the code you're using instead of playing this 20 questions lol

#

not sure what you mean by that

limpid stratus
#

yeah, at the very least, the line where you rotate the tablet map

chrome apex
#

local euler ofc

naive pawn
#

riiight so this is not what the pseudocode said

#

was the someValue playerRotation.eulerAngles.y?

#

again, try logging that, make sure it's as expected

chrome apex
#

I can try it again if you want

#

this is just trying alternative methods out of desperation

naive pawn
#

there is some weird stuff with reading eulerAngles from quaternions so maybe direction vectors could be an option, but before jumping to that just find out what the current issue is and go from there

chrome apex
#

I guess I don't need to log that, I can just keep the tablet screen selected

naive pawn
#

log it.

#

it won't necessarily be the same value.

chrome apex
#

hey, now it doesn't just spin when I turn up and down. But it doesn't seem quite correct.

Sometimes I get lines drawn to the right or to the left. If it worked, it would only draw lines towards the top, no?

#

(also, log values are the same)

limpid stratus
#

I think your tilt is messing with the output of y euler

chrome apex
#

wait

#

I think I'm an imbecile

limpid stratus
#

try clamping tilt to 89.9 and then using the player's forward vector, kill the y and normalize to determine the flattened xz

chrome apex
#

The line shouldn't always get drawn in the forward direction on the map, it just must have a positive forward direction, that's all

chrome apex
chrome apex
#

I'll make a quick snippet

#

does this seem right to you?

#

disregard all the jank and messy stuff, most of everything is for testing and unfinished

limpid stratus
#

I'm not sure. Seems so. I think the frequency at which you add points might be so low that it seems like it isn't aligned while it is.

Unrelated but I would change the alignment of the line renderer, there's an option to use the transform

chrome apex
#

I wanted to keep it fairly light but maybe I should increase it

limpid stratus
#

Also unrelated to your issue but I think an arrow marker for the player and keeping the map's orientation fixed would beat this design by a landslide

chrome apex
#

Also, we never considered the possibility that my mapping code is somehow wrong

naive pawn
chrome apex
limpid stratus
#

check for a min delta

chrome apex
naive pawn
limpid stratus
#

and it should probably create a "ghost" segment from player to previous until you lock it in place

chrome apex
limpid stratus
#

Sorry, you didn't ask for any of this. It's an exciting idea 🙂

chrome apex
naive pawn
#

but you should be on the side of the circle, the "forward" of the map would be tangent to the circle, not perpendicular to it

chrome apex
#

Yea that's what I mwant when I said all new lines should point upwardw

chrome apex
#

that's confusing

naive pawn
# chrome apex https://streamable.com/8awk61

if you just want to check if the rotation is right, have it draw anything and rotate around (in both axes) while not moving.
if that's correct but the overall map isn't right, then the drawing/saving is probably not right

chrome apex
#

so it's kinda somewhat correct, but not actually

naive pawn
#

make sure you've separated the rotation of the map and the contents of the map, though maybe the linerenderer handles that shrugsinjapanese

chrome apex
#

Yeah this last upper line shouldn't happen like this. Something is wrong

naive pawn
#

should probably thread this actually

#

a lot of context needed to help here

chrome apex
chrome apex
naive pawn
#

my gut feeling says you should be rotating the parent instead but idk if that's actually relevant

#

getting too tired for this, gonna go to sleep

chrome apex
chrome apex
#

been frustrated with this, sorry

#

gotta go take a shower

naive pawn
#

minimaps rotating according to player orientation is not an uncommon thing

chrome apex
#

yes, I believe it's the superior design

naive pawn
#

-# oh, it was adapted from how gps works, wasn't it.

chrome apex
#

you guys wanna take a gander at the mapping script? Possibly, it's not relevant but just in case

limpid stratus
#

yes

naive pawn
#

probably later, thread it

chrome apex
#

I assume I can't thread the whole convo which is a shame. I'll just drop the script now and thread it

#

!code

radiant voidBOT
chrome apex
#
public class Map : MonoBehaviour
{ 
    List <Vector3> MapPoints = new List<Vector3>();
    Vector3 lastPoint;
    float distanceThreshold = 1.5f;
    float mapScale = 0.02f;
    float yMultiplier = 0.001f;
    public LineRenderer line;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        if (MapPoints.Count == 0)
        {
            AddPoint();
        }
    }

    // Update is called once per frame
    void Update()
    {
        float distanceSquared = (transform.position - lastPoint).sqrMagnitude;

        if (distanceSquared > distanceThreshold )
        {
            AddPoint();
        }

        for (int i = 0; i < MapPoints.Count; i++)
        {
            Vector3 localPosition = GetLocalPosition(MapPoints[i]);
            // Vector3 drawPoint = transform.TransformPoint(localPosition);
            // Debug.DrawRay(drawPoint, transform.up, color: Color.yellow);
            line.SetPosition(i, localPosition);
        }
    }
    void AddPoint()
    {
        Vector3 currentLocation = transform.position;
        MapPoints.Add(currentLocation);
        lastPoint = currentLocation;
        Debug.Log("Map Points = " + MapPoints.Count);
        //Debug.Log(lastPoint);
        line.positionCount = MapPoints.Count;
    }

    Vector3 GetLocalPosition(Vector3 worldPoint)
    {
        Vector3 offset = worldPoint - transform.position;
        return new Vector3(offset.x * mapScale, 0.001f * (offset.y * yMultiplier), offset.z * mapScale);
    }
}

chrome apex
#

ah well there is a thread already. I'll copy it in it

#

dropped it there, gonna go shower now

sweet brook
#

Hey! complete beginner here, I'm using this script to open a different scene by clicking an object but now im stuck wondering how I could switch back to the main scene while also keeping the same position the Player was previously in by pressing ESC, if somebody has any pointers that would be a huge help ^^

#
public class InteractableSceneLoader : Interactable
{
    public int SceneChooser = 1;
    public override void Interact()
    {
        onInteraction.Invoke();
        SceneManager.LoadScene(SceneChooser);
    }
}

grand snow
#

The alternative is to get the player position, load the new scene, find the new player and set its position

#

If the data is stored somewhere the new scene can access then you can restore it a way of your choosing too (static field, singleton manager)

sweet brook
#

thank you!!! i'll check that out!

gaunt ledge
#

guys, fast question, what is better for performance, for me to create a LOD system that verify each prop in the map if they should appear and at which level of detail? or just use the built in system in unity?

#

there any way that is better than both of these?

frosty hound
#

Is there a problem with the built in one?

gaunt ledge
#

don't know, just want to see how much fps I can Squeeze out

toxic yacht
gaunt ledge
#

hmmm... thank you

#

we gonna have a lot of objects in these scenes so I'm trying to find ways to reduce how much this gonna heat up the pc.

toxic yacht
#

There's also ECS

teal viper
#

Occlusion culling is not really a "no brainer". It requires setup, baking, occluders and ocludees, and it wouldn't work great in some scenarios. Might even introduce more problems than it solves.

#

You might be confusing with frustum culling that is enabled by default and culls objects that "you're not looking at"(outside camera frustum).

gaunt ledge
#

occlusion culling seem to be active by default, also, already studying DOTS, but the way the project is right now I think it would take a long time for us to apply

teal viper
#

I don't think it's "active by default" anywhere.

teal viper
#

Though, I guess there's the new gpu occlusion culling in urp/hdrp, which is a totally different story. I'm not sure if that one is being enabled by default or not.

#

Doesn't seem like it is.

teal viper
toxic yacht
gaunt ledge
teal viper
#

DOTS would only help with CPU bottlenecks. And wouldn't help with GPU ones.

past cloud
#

theres a channel or something in this discord to properly setting up your ide or something isnt there

#

im using vscode and all my colours are fucked

#

im tryna find the thing that tells me how to properly fix it

teal viper
#

!ide

radiant voidBOT
past cloud
#

ty

thin cosmos
#

im new can someone teach me

teal viper
radiant voidBOT
thin cosmos
earnest trail
#

Need help

#

I have unity explorer into this game and want to change in game rank to the max level? Possible? If so how

earnest trail
#

How do I change in gam rank to max

thin cosmos
teal viper
#

We don't support moding/decompilation/cheating here

earnest trail
#

Omg

#

Lame

#

Hella lame

#

Nerd

teal viper
#

Noob😛

frosty hound
#

There's no off topic here, thanks.

thin cosmos
frosty hound
#

Yes

thin cosmos
#

i was replying

frosty hound
#

Please don't waste my time.

thin cosmos
shut helm
#

does anyone know whats the differnce between the new and old unity input systems? like i was trying to add movement to a character bc i using the newer input system so i was just queries?

teal viper
# thin cosmos i was replying

To be honest the whole interaction was out of topic(which is help with code). And you just proceeded to fueling it further.

frosty hound
teal viper
frosty hound
polar acorn
# thin cosmos no

Why are you responding to literally every question as if they were directed at you personally

smoky breach
#

I feel like a cavemand banging rocks together but i somehow managed to make the sprint function work, i have a vague idea of what i'm doing how can i improve the function?

slender nymph
#

!code

radiant voidBOT
unborn trellis
#

Hey im trying to implement a drawing minigame into my game but ive been running int
o this error that comes up when i try to click the object that activates that switches the camera over and activates the ability to draw. Any suggestions on what the issue could be + how to fix it? here are the code files if anyone can take a look + a screenshot of the line of code that the error claims is the issue

#

If anymore information is needed I'll provide it as soon as I can

keen dew
#

See the message above yours for how to post code

#

but nothing calls StartDraw that would initialize the array

unborn trellis
keen dew
#

It does, but it's inside a method that is never called so that line never runs

sour fulcrum
#

Sidenote, but instead of doing

//Getcomponent
//If getcomponent isn't null

you can do both at once via

if (hit.Collider.TryGetComponent(out MyType myReference))
  //thing with myReference
unborn trellis
unborn trellis
burnt vapor
#

And just to be sure, send the current error you're getting, even if it looks the same.

unborn trellis
#

Error comes up anytime i click on something that is processed through the raycast code, not just the drawing object

naive pawn
#

so colorMap is null

#

so StartDraw was never called

naive pawn
#

what's interactKey set to?

unborn trellis
unborn trellis
naive pawn
#

ok so it's basically a race condition then

unborn trellis
naive pawn
#

left click does 2 things, start drawing and do the actual drawing, but you haven't made it so that you do yhe "startdrawing" before you actually draw

#

colorMap hasn't been initialized at that point

#

it kinda seems like Raycast is handling too much, violating the single responsibility principle

#

so you end up trying to link disconnected behaviors together

#

the size you initialize colorMap to is set in serialization, can't you just initialize it immediately? why is it initialized lazily?

unborn trellis
naive pawn
#

uh it also seems that Raycast is written so you reset the canvas every time you draw a new line

#

Raycast overall just seems very iffy there ngl

unborn trellis
#

Well I can't change it at this point cause I have two other things that need it to activate and I got 2 weeks max to finish the game

unborn trellis
naive pawn
#

"i can't change the broken thing" yeah sure

#

the Raycast script is handling too much, that is part of the issue - it makes it way harder to work with and gives you bugs like this

unborn trellis
naive pawn
#

again, why not just initialize it immediately? was there an issue with that that necessitates the lazy load?

or even then, why not lazy load within Draw, avoiding the need for Raycast to initialize it

naive pawn
unborn trellis
#

How do I change it then? You've kept saying it's bad and not offering solutions or things to try out

unborn trellis
#

I don't know what a lazy load is and I don't know how to initialize it immediately.

naive pawn
#

ok, so say that. i don't know what you know or don't know

#

do you know what "initialize" means?

unborn trellis
#

I know what initialize means.

naive pawn
#

alright so what you have now is "lazy initialization", you're only initializing it when you're about to use it (but the bug is that you initialize it after you need to use it)

the Raycast only calling EnterDraw once you click is what drives the lazy init

#

by initializing immediately, i mean removing the initialization from StartDraw and initialize stuff once it's loaded in Start, for example

unborn trellis
#

Alright. I can try see what that does

unborn trellis
toxic yacht
#

Does it freeze completely and you have to kill unity from task manager?

naive pawn
#

are there multiple Draw components in the scene?

toxic yacht
#

Yeah I was gonna suggest reducing the resolution to something trivial like 10x10, atleast for testing

naive pawn
#

if yes then i could see why you'd want lazy init - but you'd still want to do the init within Draw, not Raycast

unborn trellis
toxic yacht
#

If it still freezes even with a small array that means you're hitting an infinite loop somewhere. Although I don't see anywhere that can happen.

naive pawn
#

oh good call, the loop on 136 has an infinite loop

#

it should be y++, not j++

toxic yacht
naive pawn
#

i thought it was temporary so i didn't consider that, mb

toxic yacht
# unborn trellis Error comes up anytime i click on something that is processed through the raycas...

The freezing is kinda its own issue. But for the null reference error, like Chris said you're running into a "race conditon" based on what you said im going to assume you don't know what a lot of these terms mean which is fine there's a lot of unknown unknowns in programming. A race condition is when you have multiple pieces of code that depend on running in a certain order, but you can't control that order. The draw behaviour shouldn't be trying to add to the canvas unless it's been initialized, so just add a check next to the on input to see if the array is null or not.

naive pawn
#

you don't need to add a check, you can chnage the flow/responsibility so you cna manage the order

#

if you just add a check then sometimes you just randomly won't be able ti draw

naive pawn
unborn trellis
toxic yacht
naive pawn
#

having the check just silences the issue, turning an error into a bug

#

either initialize immediately and not have a check, or have a check that does lazy init. the responsibility of initializing the canvas should not be in Raycast

unborn trellis
#

Hell yeah. Doesn't let me actually draw yet but does the rest of what it's supposed to and doesn't freeze the game

naive pawn
#

i think the easiest option for now would just be immediate init, and if you add more canvases and you get perf issues on initial load, then you could look into doing lazy load from within Draw

#

ideally Raycast wouldn't care about Draw either, it could look for a given interface that specifies enter/exit methods

unborn trellis
#

Alright. Any recommendations for how to code in entering drawing mode when I click on on it without the raycast?

#

Wait nevermind figured it out

empty steppe
#

Can someone explain

#

I’m 100% sure that I typed the animations the correct way

burnt vapor
#

As in, is code involved?

empty steppe
#

Ye

burnt vapor
#

Then you need to share the code

radiant voidBOT
empty steppe
#

The code itself doesn’t have an error

#

Or a warning

burnt vapor
#

Do it anyway, that's something people say all the time

empty steppe
#

Ok

burnt vapor
#

Otherwise it seems pointless to post the question here

empty steppe
#

Wait

#

The function is called out in the update function

sour fulcrum
#

!code

radiant voidBOT
sour fulcrum
#

no photos please 😄

carmine pasture
#

hello

sharp bloom
#
    private void FocusCameraMap()
    {
        Tween.Position(mainCamera.transform, new TweenSettings<Vector3>(mapCam.position, 2f, Ease.Default));
        Tween.Rotation(mainCamera.transform, new TweenSettings<Vector3>(mapCam.rotation.eulerAngles, 2f, Ease.Default));
    }

Will tweening rotation like this work well? I know some weird shit can happen when converting quaternion into euler angles (or was it only vice versa?)

#

PrimeTween doesn't accept transform.rotation directly

verbal dome
#

Weird that it doesn't have a constructor that accepts a quaternion though.

naive pawn
#

brief check in docs seem to imply that it accepts quaternions thonk

naive pawn
#

though from docs, seems like TweenSettings is intended for inspector stuff, you could also pass in those arguments directly, and Quaternion would be accepted according to docs

rare basin
#

!ide

radiant voidBOT
sharp bloom
#

My IDE says use the TweenSettings overload

dreamy scarab
#

im not sure if is a begginers question but
how much weight is a script reference?

i have a big matrix storing events, these events are added by scripts on the fly, and im planning to switch the event by solely the script holding the event so i dont have 2 scrips with the same data on a scene.

to give context ->
i have day night cycle in the game, and im adapting the time event to be more complex.

simplifying it is a matrix from classes that are separated by hour (x) and minute (y) and main stored data is a unity event list... and the day night cycle calls it each time a "minute" was changed

the hour list is fixed (24) but the minutes are added on the fly (so i dont have a 1440 empty list by default (24h * 60m->1440))

for it to work i have 2 scripts. the manager (static/single script on the scene) and a monobehaviour that i add on each thing i want a time effect (e.g. like torch that i want to enable at when its 18:30 and disable when its 5:45)

adding a element to the list is the easy part, but removing is starting to becoming confuse since i add the element directly (testing with small things didnt show any problem tho)... and i think its not memory wise to have 2 scripts with the same "variables" (unityevents in this case)

so right now thinking on switching it to a just a reference to the script with event with the said time.

polar acorn
#

1 byte

dreamy scarab
#

really?

#

._.

#

oh god

#

ok tks ^-^

wintry quarry
#

almost certainly 4-8 bytes depending on the system architecture.

#

4 bytes for 32 bit, 8 for 64 bit

polar acorn
#

It's actually like 8 bytes but the point is that you shouldn't care

#

Unless you're programming for a 1981 IBM Model 5150

dreamy scarab
#

should i bring some images?

#

i dont think its needed tho, its not that complex

naive pawn
naive pawn
acoustic maple
#

I have a ball that needs to recognize when it hits a sensor I get the the sensor a tag, but it is not recognizing the sensor

wintry quarry
acoustic maple
#

Vector3 direction = Vector3.Reflect(b_Rigidbody.linearVelocity, collision.contacts[0].normal);
float speed = 20;
b_Rigidbody.AddForce(direction * speed, ForceMode.Impulse);

#

how do I make the object go in the opposite derection it is going?

wintry quarry
#

and at the same speed or a different speed?

acoustic maple
wintry quarry
#

Just set the new velocity to the reflected direction, normalize it, and multiply by whatever speed you want

ruby python
#

Hi all, I haven't done any coding for a while and have an hour or two spare so I thought I'd have a go at a quick technical exercise for myself with Scriptable Objects. Would anyone be okay to have a quick look at these 3 Scriptable Object scripts and see if they can see anything glaringly wrong? (I don't have any data to actually populate etc. at the moment, was just trying to think my way through it. They're for a Factory game (Factorio/Satisfactory etc).

I've put all 3 scripts into the same hastebin with seperators.

https://hastebin.com/share/oqevedumev.csharp

naive pawn
ruby python
naive pawn
# ruby python Forgive the ignorance, but why not the GameObject? (Everything I've seen uses t...

using the actual component you care about makes it more explicit what the intent for that field is, it saves the indirection+necessary caching for GetComponent, if you Instantiate it you get a reference to that component directly which makes injecting references easier, and it prevents you from assigning objects that don't have said component

you'd only use Transform if you only care about that component, or GameObject if you only cared about eg its active state

ruby python
naive pawn
#

there would be a script on the root object
you'd use that script then

#

and you could have that script do the culling thing, no?

#

weaker coupling, makes it easier to work on in the future

ruby python
# naive pawn and you could have that script do the culling thing, no?

I have got a culling system that I've used before based on the Camera Frustum (it's a top down, sorry forgot to mention that), but can't remember off the top of my head where the script lives (items get added to a central list and then activated/deactivated through the list). lol. But really good feedback, thank you 🙂

sour drift
#

I’m having a problem in Unity with TextMeshPro: all my text is showing up as white square blocks (tofu characters) instead of proper letters.

I downloaded a .ttf font file and converted it into a TextMeshPro SDF Font Asset. This conversion used to work fine with the same settings before.

However, now when I reconvert the exact same font file with the same settings, the text appears as white squares.

I already checked:

  • The SDF Font Asset generation
  • I deleted the project’s Library cache folder to force a full reimport
polar acorn
#

Did you think this question was worth trying to ping 50,000 people

solar hill
#

whyyy

#

this is also not a code question either

stuck parrot
#
    {
        if (value.isPressed)
        {
            isSprinting = true;
        }
        if (!value.isPressed)
        {
            isSprinting = false;
        }
    }```  anyone knows why it doesnt toggle back to false? once I press the sprint button it doesnt go back
polar acorn
#

Ah, wait, I thought this was the usual "Both toggles happening" situation but it looks even simpler then that

#

You're calling OnSprint when you press the button, right?

#

You aren't calling it when you release the button

obtuse hollow
#

show how you set isPressed

solar hill
#

if im understanding this correctly youre basically saying "ok when the button is pressed check if the button is pressed or not pressed"

#

which is the issue... since the button is pressed

#

if you are calling OnSprint when you press the button

stuck parrot
#

ah so as soon as I stop pressing it stops calling the method

#

so how do i fix it? a do while?

polar acorn
#

How are you calling OnSprint

stuck parrot
polar acorn
#

Can you show the inspector of your Player Input component?

azure holly
#

Hi, has anyone used A* Pathfinding with Isometric Tiles before?

solar hill
polar acorn
# stuck parrot

Try logging value.isPressed before your if statements, see if it ever prints false

#

I'm pretty sure the Player Input component adds the function to both performed and cancelled

azure holly
#

The algorithm itself. My assets (characters and tilesets) are isometric so it makes things a lot more complicated. I got the algorithm to work but when I look at the gizmo debug the A* pathfinding for my ai isn't completely accurate to what my tilemap is. My tilemap is also procedural generated.

solar hill
#

Okay can you show us some more info to go off of

#

But i wouldnt say a custom A* implementation is really a beginner issue, try making a thread in #1390346827005431951

#

its also easier to contain the conversation that way

azure holly
#

I'll move over then

stuck parrot
solar hill
polar acorn
stuck parrot
solar hill
#

ive had this pfp for quite some time now 🧐

stuck parrot
stuck parrot
#

sprinting and test does

polar acorn
stuck parrot
#

i put it in update, it prints false, if i once press shift it sets to true and stays there

obtuse hollow
#

I assume this event is called all the time when you hold the buttton. You could always assume a false state at the start of the update/late update in a different bool member, then if you see "isSprinting" is true, set the new member to true and "isSprinting" to false. The new bool member should keep the state between frames and the "isSprinting" is set to false and if you keep pressing the button, it will set to true and repeat the process, otherwise it will stay false and not touch anything.

stuck parrot
#

I kinda got it working. I mean it is working fine but the code is weird. i added a variable that stores the action "Sprint" [SerializeField] private InputActionReference sprintAction; and I left the bool "isSprinting". then I got rid of the OnSprint method because I couldnt make it work reliable and put isSprinting = sprintAction.action.IsPressed(); in Update(). dont know if thats a good thing

obtuse hollow
#

If IsPressed is a simple bool read, you are good.

stuck parrot
cosmic dagger
dreamy sundial
#

Hii

#

using UnityEngine;

public class playermovement : MonoBehaviour
{
void Start()
{

}

void Update()
{
    transform.Translate(Vector3.up * 2 * Time.deltaTime);

    if (Input.GetKey(KeyCode.RightArrow))
    {
        transform.Rotate(new Vector3(0, 0, -1) * 100 * Time.deltaTime);
    }

    if (Input.GetKey(KeyCode.LeftArrow))
    {
        transform.Rotate(new Vector3(0, 0, 1) * 100 * Time.deltaTime);
    }
}

}\

#

Actually

#

I don't know why it's just making errors

slender nymph
#

!code 👇 also consider sharing what errors you are getting

radiant voidBOT
slender nymph
#

actually wait, i think i can guess even without proper context:

#

!input

radiant voidBOT
# slender nymph !input
How to Set Input

To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling

• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.

kind cape
#

Is the GorillaLocomotion Package Any Good?

pine narwhal
#

hi guys i need a quick suggestion from you, i'm working on XR simulation of Transformers and i need to show the EMF ( Electromagnetic Field visuals) around the transformer coil. what should i do with that? any suggestion will help, i have tried the SPline but i don;t think it is working as it should be, i need arrows to animate according to show the directiion of flow also. what do you think? reference picture is attached. please help

fading spade
#

I can't think of anything better.
I have an item system that needs to apply an effect to a weapon slot as well as the character stats
Is my only option to have stat wrappers kept in a dictionary indexed by enums?

fading spade
#

Or otherwise
Can property bags be used at runtime

#

I'm reading that it's more for the editor and tools rather than deployment

sour fulcrum
#

property bags?

teal viper
#

Property sacks.

#

Property bags is a real thing in unity. I was surprised with the name as well.

kind cape
#

unity is probably gonna be the only application that doesn't need age verification

burnt vapor
kind cape
#

wrong channel sorry!

rose kernel
#

what do i need to learn to be able to make minesweeper in unity?

burnt vapor
rose kernel
#

okay

verbal dome
#

The scrolling can either be done in the shader itself, or by using a material that has the UV offset exposed as a property that you can update each frame from C#

rare jolt
#

can script call another script parent's function, like the initial script get component of the other script then call their parents funcstion like TakeDamage();

naive pawn
#

a class can call its own parent's method via base though, that can be useful for composing behaviors

verbal dome
rare jolt
verbal dome
#

By parent do you mean the parent object in the transform hierarchy, or the parent class of the other script class

rare jolt
#

parent class

verbal dome
#

Maybe I don't understand, but why wouldn't you be able to call TakeDamage on the other script if it is public?

#

Show example code of what you want to do

#

(If what Chris said didn't answer your question)

red snow
#

😎

rare jolt
polar acorn
rare jolt
#

i'm asking to answer my whatif as i'm still learing unity programming like inheritance. like i try to find some reason to use it like for base character script to tidy up my scripts

rare jolt
polar acorn
#

All child classes are instances of the parent class except where you have explicitly overridden functionality

rare jolt
#

then if call this function from child script, how to change the parent health variable into my child script health

verbal dome
#

It's the same variable

#

Child inherits health from its parent

rare jolt
#

yes but i don't want all enemy with the child script to have same health and if i'm not wrong, i need another health variable in child script

verbal dome
#

You don't need another variable for the child for that

#

Just set the child's health to a different value in the unity inspector

#

You can also use properties for different default values for child classes, something likecs // parent public virtual float health { get; set; } = 100; // child public override float health { get; set; } = 7;

#

But just changing the value in the inspector is simpler, unless you want to really practice virtual/overrider here

#

Using properties here also makes it "hard-coded" per each class, while adjusting it in the inspector you can do whatever - even have the same exact script class on different objects but with different starting health

cobalt gorge
#

can someone help me? i installed inventory asset in my project and after initializing im getting this error

InventorySystem.InventoryController.AllignDictionaries () (at Assets/InventoryAsset/InventoryController/InventoryControllerScript/InventoryController.cs:424)
InventorySystem.InventoryController.Awake () (at Assets/InventoryAsset/InventoryController/InventoryControllerScript/InventoryController.cs:94)```
#

this is in code

sour fulcrum
#

is there a inventoryuimanager script on that object

keen dew
#

That disclaimer in the inspector doesn't really give much confidence in the quality of that asset

ionic zealot
#

Laddies, can yall help? Idk why the enemies dont play the death animation if there is more than one in the scene(otherwise its fine)```c#

#

Why did it send like that!?

livid socket
#

message too long maybe

polar acorn
radiant voidBOT
cobalt gorge
polar acorn
# cobalt gorge

So either inventoryInstance or inventoryUIDict is null. Use logs or the debugger to find out which.

ionic zealot
polar acorn
ionic zealot
#

It runs for sure, cause it gets offset like in the 222. line

polar acorn
#

Then follow-up: Are you sure that you're calling it on the right instance? And that every instance is properly referring to its own animator?

ionic zealot
#

The thing that's weird is that if i have only one enemy it works perfectly, but as soon as i do it with multiples it breaks

polar acorn
#

That usually means you have something that isn't a direct reference, you're calling a function somewhere through a static variable or something non-deterministic like Find

#

Or that you're calling functions on prefabs instead of instances

cobalt gorge
#

okay i dont have this error now after doing everything again, but i dont see inventory

polar acorn
cobalt gorge
#

The Child of Inventory Controller, InventoryUIManager is active. Disabling it now.
UnityEngine.Debug:LogWarning (object)
InventorySystem.InventoryController:TestChildObject () (at Assets/InventoryAsset/InventoryController/InventoryControllerScript/InventoryController.cs:713)
InventorySystem.InventoryController:Awake () (at Assets/InventoryAsset/InventoryController/InventoryControllerScript/InventoryController.cs:93)

sour fulcrum
#

maybe ask the author of the asset

polar acorn
cobalt gorge
#

its not my code sadly. i wanted to use someones asset but now im fighting with it 2 hours

dense basin
#

I clicked 'Generate Shader Includes' and the screen turned black like this. Could you help me figure out how to restore it?

solar hill
#

might have messed with the material you use there

verbal dome
#

I say just ditch it, find another one or make your own if you want to learn

solar hill
#

theres that one by more mountains

#

i heard good things

cobalt gorge
#

im searching for free one

solar hill
#

an inventory system is surprisingly not that complex

cobalt gorge
#

im gonna try to do

#

can you send me good tutorial?

#

i want to make something with this style

#

just like that

solar hill
#

youre confusing 2 different things, which is the actual functionality of the inventory system vs the UI representation

#

handle both issues separately

#

as for tutorials.... well i got nothing other than the stuff you can look up on youtube

sage mirage
#

Hey, guys! I am not sure but I am getting this error when transitioning from one scene to the other after the game is over. Here I have my EnableGameMode() method where the error occured.

slender nymph
#

show code

sage mirage
#

Which part exactly because I have much?

slender nymph
#

the code where the error is happening

sage mirage
slender nymph
#

that's the stack trace. now show the code.

sage mirage
#

wait a sec

#

So its basically here

naive pawn
#

!code

radiant voidBOT
naive pawn
#

you didn't even include the line numbers

rich adder
#

havent you been here long enough to know this

sage mirage
#

I am yes but I didn't know what exactly I have to send

#

I mean I have so much code

naive pawn
#

the stack trace tells you

sage mirage
#

yes

naive pawn
#

these are the relevant files, classes, methods, lines

sage mirage
#

ok give me a minute

verbal dome
#

You used a paste site with no line numbers :/

sage mirage
#

omg everything goes wrong XD

rich adder
#

also you need to send the entire class not just the function or the lines are useless

slender nymph
#

there are several sites in the bot embed, choose one of those

naive pawn
#

(of which the first 2 are broken, choose one of the latter 2)

#

wasn't that bot embed updated or smth, and got reverted i guess? or am i wildly misremembering

rich adder
#

pastemyst always been the best

solar hill
#

and that sidias site was added

#

but apparently not?

naive pawn
#

i recall it getting 4 added and the 2 broken ones removed

rich adder
#

first 2 have been broken more recent but who knows

naive pawn
#

first 2 have been broken for quite a long time

rich adder
verbal dome
#

They took minimalism too far

naive pawn
#

lovely, minimal information

rich adder
#

yay

naive pawn
#

and a whole tutorial

verbal dome
#

It's like a good 3-4 seconds to open any page

#

On phone or PC

slender nymph
#

yeah, it's pretty slow. at least it works though lol

verbal dome
#

Yeah the bar isn't very high

sage mirage
verbal dome
#

Ffs

solar hill
#

this is almost very hilarious

naive pawn
#

used to be in like, 2020 you could just google "pastebin" and all the top 10 results were fast, auto-expiring, had proper highlighting, code lines, code folding, searching, highlight references

rich adder
#

titleUI
is the null in UIManager.cs

solar hill
naive pawn
#

it's loading for me but the textarea isn't getting styled 😂

sage mirage
#

it was loading

naive pawn
#

502 means the server died or hiccupped

verbal dome
#

It also doesn't have syntax highlighting

#

We can't win it seems

rich adder
#

@sage mirage how did you assign titleUI inspecotor ? cause it goes null when you try to use it again

naive pawn
#

i don't think it's titleUI

#

the error says GameObject

#

that aligns with the thing getting SetActive called on it

rich adder
#

oh probably trying to activate a null object ?

naive pawn
#

titleUI.modesMenu is the one that's been deleted

#

if i had to guess, it got unloaded

#

when transitioning from one scene to the other
yeah it got unloaded, stale reference

fickle plume
sage mirage
# rich adder `titleUI` is the null in UIManager.cs

Basically on two of my scenes I have made bridges and I am assinging some references at runtime probably something breaks when I am transitioning from main scene to title scene so when the game ends there is a short timer and automatically my game returns back to menu but if I press all the time like spamming any key for example then it prints that error you have seen before. Do you want to see the bridge mono behaviours I have?

rich adder
sage mirage
#

Its kinda of DI

verbal dome
#

My criteria for paste sites:
-Fast
-Syntax highlighting (without having to manually select it)
-Line numbers

naive pawn
sage mirage
#

dependency injection but not exactly its seems to be

#

And something breaks

naive pawn
slender nymph
# sage mirage stale reference?

all gameobjects in the scene are destroyed when another scene is loaded in Single mode. because titleUI.modesMenu is referring to one of those objects, it has a no-longer-valid reference when you switch scenes

naive pawn
#

did you use DDOL on modesMenu? (you shouldn't, just pointing out the issue)

slender nymph
#

for the singleton, yes. but not those other objects that it references, right?

sage mirage
#

Let me send you the bridges I have

#

that will make things clearer

naive pawn
#

it's already plenty clear

sage mirage
#

because there things are happening at runtime the assignments etc I want to persist

#

across scenes

naive pawn
#

your persistent singletons should not reference non-persistent scene objects

#

because the persistent singleton has a longer lifespan than the non-persistent scene object

sage mirage
#

So you said it is unloading the modeMenu object specifically?

slender nymph
#

ah, I found your SetTitleUI method, i'm guessing that's not getting called before this other method that is throwing the exception gets called

naive pawn
sage mirage
#

I do think the problem has to do with timing because I see all the references there when the scene transition happens. Let me send you another video and the title scene bridge script I have.

#

because it only happens when I spam keys on transition

#

so any input I have for gameplay on my game

#

liek movement, shooting, select modes with W and S buttons

#

and any key down for the press start

#

at this moment only

#

I figure out the issue

#
{
    #region LOCAL REFERENCES
    [Header("LOCAL REFERENCES")]
    [SerializeField] private TitleSceneRefs titleRefs;
    #endregion

    private IEnumerator Start()
    {
        yield return null;
        UIManager.Instance.SetTitleUI(titleRefs);
        ResetCreditsUI();
    }
#

I did in Start() Ienumerator and used yield return null

#

wait I think I found the issue

#

Let me test it one more time

#

Yes that was the issue guys

#

I comment out this specific line I dont see the issue anymore when spamming any keys before and after transition

#

But why? Here is the important question.

simple hawk
#

hey guys, trying to set up git lfs, at the point where I need to track the necessary file types; is there a way I can make this easier? got a bunch of Unity file types and I don't feel like scrolling through files and entering all the file types

slender nymph
simple hawk
slender nymph
#

replace your existing .gitattributes file with this. or if you don't have one already (which you should if you're setting up lfs), then just download this to the root of your repo, it should be named just .gitattributes

simple hawk
slender nymph
#

unless you have anything specific you've put in there yourself, in which case don't replace that part obviously

simple hawk
#

phew, thank you so so much, was worried I had to sit here for hours inputting all the file types

fleet iris
#

Hey all, I'm trying to create a player controller and am following this guide from 2021 by Sebastian Graves on YT. I know it's old, but it's the only one I can somewhat follow along to. Anyway, this issue I'm finding is at line 17 where it says that movement hadn't been declared, so what should I do specifically?

naive pawn
fleet iris
ivory bobcat
#

You'll need to show us

naive pawn
sharp bloom
#

Do you have a "rule of thumb" on the size of a class?

#

Is 400 rows getting too large?

white girder
#

No

ivory bobcat
#

Follow the C# SOLID design principle

red hull
simple hawk
#

I have a problem, I have tracked .dylib in git attributes, but for some reason the file isnt being converted by LFS, what do I do?

grand snow
simple hawk
grand snow
simple hawk
#

I think I did, iirc I added it to the .git attribute, commited that, then tried this

#

unless I misunderstood the question

grand snow
#

If commited not in lfs, then in lfs then the file still exists in git history outside of lfs. Meaning you can never push this commit to github

#

Meaning you cannot push the branch

simple hawk
grand snow
simple hawk
#

gotcha

grand snow
#

Try using it with a filter of files over 99MB

simple hawk
#

ok

simple hawk
grand snow
simple hawk
wicked stratus
#

I'm setting up my dialogue in csv format, specifically in google sheets, then export as csv. I have a few questions about this, though, especially since my game will be pretty text heavy. I want to make sure the approach I take here is scalable.

1: what is the most efficient way to handle this/what is standard? When does fetching start becoming slow? Should I break up the text into many different files, so if it's searching, it doesn't have to search through a big list, or is that sort of searching relatively trivial for computers to handle and won't matter much?
2: Is it standard to cache bits of data somehow? If so, where can I find more information about this?
3: Would it be better to like, convert the CSV to json and have it handy in an object in the scene, or do I want to read the CSV file each time dialogue needs to be called? Should I look into database management, or is that unnecessary/overkill? Is there a way I shouldn't due it due to inefficiency? I want to make sure my solution is both scalable, efficient, and fast, and I'm sure this has been figured out by people both smarter than me and who had to find out themselves, but I have a hard time knowing what to look up for more information on this.

Currently, my plans are to make a script for parsing the CSV, and whenever text needs to be rendered in game, it opens and reads the file, iterates through the file for the text ID (usually something long such as CharacternameDialogueGraphResponse1 or so) and pulls that entry. But I could see that getting slow pretty fast especially in later parts of the game where the entries are farther down the list- I could also see that being trivial work for a computer, I'm just not totally sure. if I need to worry about that.

echo palm
#

Holy ai

wicked stratus
#

no!

echo palm
#

@echo palm

wicked stratus
#

I hate ai

echo palm
#

Yeah right

#

Like you don't vibe code all day

grand snow
wicked stratus
#

I don't vibe code!!!

echo palm
#

I out here actually xodin

grand snow
#

But its not wise to load a lot of data into memory at once as well as having a file soo large it takes ages to parse so splitting things up will help

wicked stratus
grand snow
#

If it can be hidden in some loading sequence and it takes hardly any time (less than 1s) then its probably fine

#

but trying to load during gameplay and it causes lag? bad times

wicked stratus
#

that's fair haha.
So maybe before build, write a script that goes through the file and loads it into an object, then save that object? and then maybe still caching scene relevant dialogue via a different object

grand snow
#

If parsing from csv to some other format helps then go ahead but that can be done in unity via a custom importer

#

but then the data still has to be read from disk if a unity asset but that may be faster

#

Binary formats are best for parse speed, text formats that require complex parsing are slower

wicked stratus
#

I'll look into this, thank you

grand snow
wicked stratus
#

I'm still a little confused, because at some point during runtime, dialogue will need to be fetched, I don't know how to best have it be easily retrieved in memory, though. Would the importer help with that?

#

What is standard/good practice for getting it ready to be retrieved easily?

#

what I'm gathering so far is that I should probably read and process the csv into the game before build/it shouldn't happen via runtime, but im not sure of the mechanisms of that, like what that processing result should be.

grand snow
#

A scripted importer would just automate unity parsing the file into an asset. You would still then "load" the asset like any other unity asset

#

Id still split up content into seperate assets as the issue of "loading to much stuff into memory" is still there

wicked stratus
#

Okay, this is a good jumping off point, I super appreciate it, thanks!

echo palm
#

Hi guys

#

Who wants to code air

#

Like just IRL aor

#

In irl

timber tide
#

just frontload all text ;)

#

I was actually trying to make a word game, but I ran into a problem that if I loaded in a bunch of dictionarys worth of words then I'd implode the user's device, but if they weren't loaded then I couldn't accurately challenge the words given that quickly.

sage lotus
#

hi, new to the server and unity.
is there a good place to find example code?
trying to figure out how to get InputSystem to work with Character Controller component instead of rigidbody but no luck since nothing i find through searching is detailed enough to help me understand

#

figured if I could see an example of a script that works, it'd help me continue learning

#

even for basic thing like moving on X and Y

timber tide
#

Unity has some controller templates that uses the character controller

sage lotus
#

yeah I looked at this one, but the script is so complicated idk what I was looking at

timber tide
#

yeah can be bulky. Honestly the newer InputSystem is a little tricky as it works mostly on events instead of polling in the update loop like a lot of more older engines do

#

which you can still do, just more encourged to do it with events

sage lotus
#

I was reading that inputsystem is more flexible and easier to understand, just can;t find anything useful on how to get it to work without a rigidbody

timber tide
#

well, rigidbody has a bunch of ways you can control it. CharacterController you'll be constantly setting a velocity each update somewhere

sage lotus
#

yeah, that's the appeal

#

it's hard for me to explain in words without a multipage essay, but I don;t think rigidbody is the best choice for my idea

#

so that's why I am asking if there's a way to get the ease of InputSystem, without needing a rigidbody

timber tide
#

I'd post the script that you're having trouble figuring out the differences between how it's set up.

sage lotus
#

I've tried so many different emthods I found searching. but nothing is working.

if there's a basic example of them working together, even to just move on the X and Y. it'd be very helpful

timber tide
#

Besides the method calls, it should be very similar, but CharacterController does prefer calling the velocity method inside of Update over Fixed

sage lotus
#

oh heck. I missed this. man Google search is ass these days. it never even showed me the docs page in these 3 days I've been looking

#

lol. I'll read through this.

timber tide
#

That actually doesn't use events, it just polls the actual input

sage lotus
#

thanks for the patience. I am very new and ignorant right now

timber tide
#

Like technically this can be an input method

jumpAction.action.WasPressedThisFrame())

So instead of checking each frame it would flip it once and you can append the velocity next frame

#

I think the 3rd person controller has it like this:

void OnJump(InputAction.CallbackContext ctx)
{
    Jump();
}```
sage lotus
#

oh so either works?

#

like void OnMove and all that

timber tide
#

It's just the more intended way to use the InputSystem. It's cleaner, but I wouldn't call it any more performant than just checking it in update like above.

#

Like people do love keeping their Update loop clean

sage lotus
#

I'll add those to me checklist of things I need to read up on

#

I got frustrated before and closed the editor for now, so I'll test these things out later and just search for more documentation for now

#

thanks again for the help. this seems like a good point to start learning again

#

the unity learning projects are all about getting the results, but not explaining why things are the way they are so they only helped so much

hallow sun
#

So i read that separating UI element over various canvases makes it more efficient because it redraws everything on someting moved, what's the line on this?

I have 8 scroll views and I'm thinking of putting each on its own subcanvas, because the user can only move one at a time so the other ones don't need to get redrawn.

Is this good? Idk how expensive a subcanvas is on its own so the benefit might not be enought to warrant using them.

teal viper
timber tide
#

it works similar to that of sprite renders and the dynamic batcher. It tries to bake all the sprites currently being rendered into a single drawcall by combining it

#

but the thing with sprites is they are usually always dirty as the scene is always changing. UI can be pretty much static and only ever needs to do is to draw itself again, but if you modify an element then it dirties it and needs to do that whole combining process.

rare jolt
#

want to create a probability system that is changable but don't know how to implement the second part( the second forloop).

teal viper
rare jolt
#

more specifically, i want to be able to edit the numbers in the list of attack probability array. the first forloop is to combine all the numbers(the sum) in the array and the second try to find each iteration chances to trigger

#

sorry if not explained clearly as i'm not good at explaining in details

#

just to say my main problem is that i want my second forloop to find the right number(%) but this solution doesn't quite work

acoustic sequoia
#

Hello everyone, hope everyone is having a great day.

I had a couple questions about how I want to save my game data. is this the right place for that?

radiant voidBOT
# naive pawn !ask

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.

-# For more posting guidelines, go to #🌱┃start-here

naive pawn
narrow idol
#

hello

rare jolt
naive pawn
rare jolt
#

ah i see, then its weight

naive pawn
#

probability of a given element is its weight divided by the total weight

acoustic sequoia
#

Can someone tell me why i am getting this in my save data? there should be more information in gridData. or is this instanceID thing normal?

{
    "saveName": "first save",
    "saveTime": 1776405157157,
    "gridData": {
        "instanceID": -26260
    }
}
teal viper
slender nymph
#

i'm gonna guess that gridData is a MonoBehaviour or a ScriptableObject, in which case this is expected behaviour when serializing a reference to one of them

acoustic sequoia
# teal viper We can't really answer that without you providing more context. We don't even kn...

here is the class i want to save in gridData:

[System.Serializable]
    public class GridData : MonoBehaviour {
        [SerializeField] public NewDictionary data;
        [SerializeField] public Vector2Int[] positions;

        public GridData SaveFormat() {
            positions = new Vector2Int[data.dict.Length];
            var index = 0;
            foreach(var item in data.dict) {
                positions[index] = item.id;
                index++;
            }

            return this;
        }
    }

    [System.Serializable]
    public class DictionaryItem {
        [SerializeField] public Vector2Int id;
        [SerializeField] public Cell item;

        public DictionaryItem(Vector2Int id, Cell item) {
            this.id = id;
            this.item = item;
        }
    }

    [System.Serializable]
    public class NewDictionary {
        [SerializeField] public DictionaryItem[] dict;

        public Dictionary<Vector2Int, Cell> ToDictionary() {
            var newDictionary = new Dictionary<Vector2Int, Cell>();
            foreach(var d in dict) {
                newDictionary.Add(d.id, d.item);
            }
            return newDictionary;
        }

        public DictionaryItem[] ToSerializedArray(Dictionary<Vector2Int, Cell> currentDictionary) {
            var array = new DictionaryItem[currentDictionary.Count];
            var index = 0;
            foreach(var kvp in currentDictionary) {
                    array[index] = new DictionaryItem(kvp.Key, kvp.Value);
                    index++;
            }
            dict = array;
            return array;
        }
    } 

here is the saving method:

GameData loadData = SaveManager.LoadGame(SaveName);
      if(loadData == null) {
        _cells = gridManagerObjects.InstantiateCellGrid(startMatrixSize);
        gridData.data.ToSerializedArray(_cells);
        GameData data = new GameData(SaveName, gridData.SaveFormat());
        SaveManager.SaveGame(data);
      }```
#

i want the Vector2Int[] array in the grid data to show in the JSON file if i want it to load the game, correct? my question is about this InstanceID thing. should it be showing the InstanceID to read the array of vectors, or does the array of vectors need to be showing?

teal viper
#

Instance I'd is part of the MonoBehaviour. It's not useful for you in any way.
Evetything else doesn't appear probably because it's not serializable.
Im not sure if vector2int is serializabpe or not.

#

Also, how are you actually serializing it(creating the json string)?

acoustic sequoia
#

hmm ok, so i'll try to throw in some basic data types with hardcoded data to see if it appears to see if the vector2Int is a prob

acoustic sequoia
teal viper
#

I think the main issue is that GameData only contains a reference to the grid data.

#

I don't think json utility serializes recursively.

#

If you don't care about the type, making it a struct, should help.

acoustic sequoia
#

I'm asking for help at this early stage because this save file will eventually be massive... so i want to successfully organize this in a clean way... do you have any recomendations on books to read on this topic (specifically for unity JSON saving)

#

or is there a simple fundamental mindset I should have throughout this learning process?

teal viper
#

I'd start from googling. But generally, your options are: savdump everything into one file or several. If you expect huge sizes and complex data structures might want to consider binary as json can get very slow very fast.

teal viper
#

You might think that I'm being lazy to give you a proper advice, but the truth is that even experienced devs, don't hold everything in their heads. We have to reread docs every time we touch a feature we didn't touch for a while.

acoustic sequoia
teal viper
#

And the most convenient one too.

#

I'd start with getting it working first.

acoustic sequoia
#

but you help has been helpful. i have a new mindset about it already so my brain is cooking up better googling questions now thanks to your help ❤️

burnt vapor
acoustic sequoia
burnt vapor
#

If you truly want a proper save system then you'd ahve to make a system that uses a BinaryWriter and a BinaryReader, but the simpler option (at least during development) is serialization using JSON

burnt vapor
#

JSONUtility will probably be faster, but that's only because it's so limited that it doesn't have to bother with most things

acoustic sequoia
burnt vapor
#

The only issue is that Unity has very bad practices and it causes bugs, like Vector3 types not being serializable by the default. However, packages exist to solve this issue.

acoustic sequoia
#

i will start reading those DOCs then! thank you. these are the time savers i'm looking for!

acoustic sequoia
burnt vapor
#

Feel free to ask here about it, I think most people know Newtonsoft

#

Even more ideal would be to use System.Text.Json, but support for that doesn't properly exist in Unity yet. It is possible, if you spend time making it work. It's a very performant solution in that case. But even if you plan on using it then you might as well use Newtonsoft and migrate later (which is quite simple mostly)

teal viper
burnt vapor
#

Tha's a big ass save then 😄

teal viper
#

Minecraft saves for example.

acoustic sequoia
burnt vapor
teal viper
acoustic sequoia
#

interesting. well guys, thanks for the help tonight. going to get some rest and going to start my doc reading adventure tomorrow at the earliest convienence. wish me luck. i'll probably be back in here tomorrow with a couple good questions

burnt vapor
#

BTW @acoustic sequoia the only reason JSONUtility doesn't have this issue is because it serializes fields, not properties. If you switch over that is something you need to take into account.

#

Just to be clear, the proper way would be to serialize properties. That's always the expected behavior when it comes to serializers. The fact JSONUtility serializes fields instead is an issue.

strong wren
#

!collab @feral stump

radiant voidBOT
ripe oyster
#

I'm trying ot make a drag and drop system for the balls. however when i try the 'onmousedown' method, nothing happens or registers

[RequireComponent (typeof(Rigidbody))]
public class MouseMovement : MonoBehaviour
{
    Rigidbody rb;
    Vector3 mousePosition;

    private Vector3 GetMousePos()
    {
        return Camera.main.WorldToScreenPoint(transform.position);
    }
    private void Awake()
    {
        rb = GetComponent<Rigidbody>();
    }

    void OnMouseDown()
    {
        mousePosition = Input.mousePosition - GetMousePos();
        transform.position += Vector3.up;
        rb.useGravity = false;
        Debug.Log("apple");
    }

does anybody know what i did wrong? i already checked if there is nothing between the camera and the orb

teal viper
ripe oyster
teal viper
#

Are these the default settings for the colliders?

ripe oyster
#

yes as far as i know

#

haven't touched them

teal viper
#

Okay. And you don't see the logs from the method in the console?

ripe oyster
#

nothing on any of the orbs. it's supposed to give something when the mouse is pressed once the mouse is over them, but nothing happens

teal viper
#

I don't remember for sure, but it could be that this doesn't work when the new input system is enabled. That or it required an event system with a physics raycaster.

#

Though, the docs don't mention it. 🤔

verbal dome
#

My thought process was the same

ripe oyster
teal viper
#

Well, you can always do a raycast from the camera.

#

Honestly way better than ambiguous old magic functions.

ripe oyster
#

probably true, get raycast from mouse, check what object it is pointing to, change the transform of the object to the transform of the mouse.
i'll take another look. thank you

verbal dome
#

They're not on the IgnoreRaycast layer are they? :D

livid notch
# ripe oyster I'm trying ot make a drag and drop system for the balls. however when i try the ...

Am kindly please check these things first?

  1. Does your ball have a Collider?
    Rigidbody alone is not enough. Your object needs something like a SphereCollider, BoxCollider, or another Collider component. Unity's docs are explicit that OnMouseDown is called when the mouse is over the object's Collider.

  2. Is this script on the same GameObject as that Collider?
    OnMouseDown is sent to scripts on the GameObject with the Collider. Parent/child objects do not receive it automatically.

  3. Is the object on Ignore Raycast?
    If yes, Unity will not call OnMouseDown.

  4. Are you actually using 3D physics?
    Your script uses Rigidbody, so this is a 3D setup. If your "balls" are 2D objects using Rigidbody2D, then this script is the wrong setup. Current Unity docs note that OnMouseDown can work with 2D colliders too, but only if the object has the right collider setup.

teal viper
#

Most of this is seen on their screenshot...

verbal dome
#

Getting AI vibes since it clearly says they are using Rigidbody not 2D...

ripe oyster
ripe oyster
#

anyway, back to trying the raycast method

livid notch
verbal dome
#

Nothing wrong with learning, but if they want AI help they can easily do it themselves

ripe oyster
#

i've had a bit too much halucinating with AI. so unless i have a detailed plan and only need the names of different options, then i use it. but if i don't even know what method i'll be using i usually skip it and first try to figure that out

livid notch
ripe oyster
torpid vault
#

I am trying to make a 2D fighting game and have a question about IEnumerators. Code example:
public IEnumerator Attack()
{
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(center.position, radius, attackMask);
foreach (Collider2D enemy in hitEnemies)
{
Debug.Log("Hit");
yield return new WaitForSeconds(2);
}
}

If I use StartCoroutine(Attack()), is the Collider "hitEnemies" active for 2 seconds or is it just active for one frame and then there's a 2 second delay?

wintry quarry
#

OverlapCircle is an immediate physics query - it checks the state of the physics world at the exact moment you call it

verbal dome
#

What do you mean active?
The Overlap method returns that array of colliders, and it exists until the coroutine stops

wintry quarry
#

The only thing you're delaying in this code is your Debug.Log between each iteration of your loop.

torpid vault
verbal dome
#

It all happens immediately when you call OverlapCircleAll

#

Some of the colliders in the returned array could even get destroyed between the waits

torpid vault
#

Thank you, I understand it now

tame flume
#

Is anyone able to answer questions pertaining to Wwise with Unity?

verbal dome
sage mirage
#

Hey, guys! Btw, I found a way to actually persist objects across scenes which is not using DDOL. It's called Bootstrapping. For my game, what I do is I have 2 mono behaviours and I am assigning references at runtime when the scene loads also I am using DDOL for Singletons. Could you please help me understand Bootstrapping and how do we use it?

wintry quarry
verbal dome
#

Are you talking about "bootstrap scene" in particular?

wintry quarry
#

Some people use a "bootstrap" scene in Unity - i.e. they make their initial scene a "setup/bootstrap" scene, and then they additively load other scenes, keeping the bootstrap scene around with all the persistent stuff in it

#

Maybe that's what you're seeing

sage mirage
#

btw DDOL is also loading scene additively

#

DDOL is actually a new scene Unity creates for us and loads additively no?

wintry quarry
#

yes, correct, but it's a special, built in additive scene

#

You're right in thinking it's a similar concept though

#

ultimately additive scene loading is the key

#

and having a scene that "sticks around" when others go away

#

Whether you make your own, or use the DDOL one, doesn't matter

sage mirage
#

but I really cant understand the difference between those two. With DDOL we dont destroy Singletons right and if I move to a new scene afterwards it will keep my singletons across scenes right? What happening with Boostrap Scene is it only initializes stuff/objects within this bootstrap scene and then whenever we need them we are loading them on new additive scenes? I think I confuse those two.

#

There isn't also in Unity Docs anything to read about Bootstrapping

sour fulcrum
sage mirage
#

Hey, guys! I have a question. Why I can't use Random.Range() on my fields declaration area?

#

It says I have to do it in Start or Awake instead

keen dew
#

Field initializers must be compile time constants. Random.Range is doubly not that because it's a method and it returns a random value

grand snow
#

c# has no const functions too 🙁

slender nymph
#

field initializers just need to be static so normally a static method like Random.Range would be fine, howeverfield initialization will happen on a separate loading thread, and most unity APIs can only be used from the main thread so it will throw that exception
https://docs.unity3d.com/6000.3/Documentation/Manual/script-serialization-best-practices.html

Most Unity APIs can only be called from the main thread. Don’t call Unity APIs from constructors and field initializers of serializable types because these run on a separate loading thread.

sage mirage
#

Hey, guys! I have a question. The main difference between speed & velocity is that speed is only speed and velocity has both direction and speed? I was just wondering what's the differnce

obsidian shoal
#

hey fellas. Is there a way to prevent textfield get focused with keyboard inputs?

verbal dome
#

Pretty sure that's it

brave compass
#

In that sense, a position is also just a direction and distance from the center, but we generally just call it a vector.

sage mirage
night raptor
#

3D vector is literally 3 numbers, you may interpret is as you wish

sage mirage
#

I mean it is a vector but in the context of vectors a point itself doesn't have a direction and magnitude

night raptor
#

point is 3 numbers, a vector. the vector interpretation would be a direction from the origin outwards and has the magnitude of distance from the origin

#

Vectors in code are usually only represented by those 3 values. There is no separate direction and magnitude though you can calculate them from those 3. magnitude = sqrt(x^2+y^2+z^2)

thorny merlin
#

Created a rotate speeduptest function in the first script and passed rotatespeed variable as arguement when calling speed up in the second script. so why does rotatespeed not go up by 100? i thought it shhould constantly go up by 100 every frame but it doesnt seem to change when i press play?

night raptor
thorny merlin
#

so how can i modify the actual value of rotatespeed?

night raptor
#

Out (ref actually I think) parameters are one way. I generally don't like that workflow though. Why does the value need to be changed in separate class? I would much prefer CalculateNewSpeed(int currentSpeed) which returns the new speed but doesn't modify anything.

#

You could then do speed = CalculateNewSpeed(int speed)

thorny merlin
#

so set the return value as the new value for the rotatespeed?

#

okay i see, thanks for the suggestion

night raptor
#

np. Be cautios that whatever you are doing is not going to be framerate independent. With higher framerate you will have the speed value increasing more rapidly.

thorny merlin
#

yeah i understand that. i'll implement time.deltatime wherever necessary. just thought parameters can change variable values

night raptor
# thorny merlin yeah i understand that. i'll implement time.deltatime wherever necessary. just t...

It would be logical to think that way but function parameters are copies and therefore only change the local copy. The matter is different with reference types, lets say you passed in a list of values, modifying that list in the function will also modify the list from the caller. Why it works that way for reference types is that still a copy is passed, but a copy of a reference this time. That means both Lists (or whatever reference type you use) have a reference to that same object

thorny merlin
#

as in reference variables?

#

i mean do you mean reference variable by reference types?

night raptor
thorny merlin
#

i see, ill have to look into it.

#

again thanks for the help

night raptor
#

you are welcome

languid holly
#

Is there a way to learn the code rather than watching tutorials?

obsidian shoal
cosmic dagger
languid holly
#

Thanks

plucky copper
#

I am having an issue. I created a minimal example to reproduce the issue.

https://code.7imezones.com/vhalragnarok/UnityCameraMouseIssues

(Unity 6.3 LTS).

My Character is not rotating correctly to face the mouse.

I am using new Input and have the PlayerInput as a C# class and hook into the performed events.

I am using the Character Controller.


Ray ray = Camera.main.ScreenPointToRay(_aimDirection);

if (!Physics.Raycast(ray, out var hitInfo, Mathf.Infinity, _aimLayerMask)) return;

Vector3 lookDirection = (hitInfo.point - transform.position).normalized;

lookDirection.y = 0f;

transform.forward = lookDirection;

I am running this code in the update loop, however the hitInfo.point is wrong. I am using Mouse Position on the update.

The only quirk is I am using Cinemachine, I have a follow camera (world space) & rotation composer.

_aimLayerMask is serialized out and _aimDirection comes from the .ReadValue<Vector2>() from the OnAim(InputCallback value) Event Handler.

What could be causing this beyond Cinemachine? I feel like this should just work.

verbal dome
obsidian shoal
#

oh i see. thanks!

wintry quarry
plucky copper
wintry quarry
#

"aim direction" doesn't sound like a screen space mouse position

#

You said :

aimDirection comes from the .ReadValue<Vector2>() from the OnAim(InputCallback value)
But how is that configured? Is OnAim even running? What are the settings on the Aim action?

#

If OnAim never runs and _aimDirection is always 0, that could explain why it's always facing towards the bottom

#

You need to debug your code

#
  1. Is OnAim running and getting the correct mouse position data?
  2. Is the raycast hitting anything?
  3. If the raycast is hitting something, what is it hitting?

^ Use Debug.Log or a debugger to find the answers to these questions and your problem will reveal itself

plucky copper
#

So. hitPoint is showing garbage.

#

_aimDirection is sensible.

#

I am only able to rotate in the bottom half of the screen.

#

Which leads me to blame Cinemachine / my top-down camera skewing things.

sour bobcat
#

Hello, I have the following issue when trying to modify/write code in scripts and I really don't know what to do anymore, Intellisense doesn't seem to work. I've reinstalled VS, and Unity, created multiple projects, installed the .NET microsoft sdk but still nothing

swift crag
#

did you follow the instructions in ...

#

!vs

radiant voidBOT
# swift crag !vs
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

swift crag
#

this article?

sour bobcat
#

Aye

swift crag
# radiant void

you've done a bunch of stuff, but you might've missed something important from here

#

gotcha

#

can you right click on "Assembly-CSharp"? I remember seeing a problem where you just have to tell it to...not be unloaded

#

(I use Rider, so I'm not super familiar)

sour bobcat
swift crag
#

hit Reload Project with Dependencies

sour bobcat
#

I get this

left pilot
#

weird question can anyone link me a guide to networking for a 2d game in unity? I created my game but possibly want to make it multiplayer and havent really done networking.

surreal coyote
#

Hi, does anyone know if its possible to sync the default ocean system for multiplayer? I imagine not but thought id ask before building my own system

wintry quarry
#

If you're feeding _aimDirection into Camera.main.ScreenPointToRay(_aimDirection);
Then you need to construct it like this: _aimDirection = new Vector3(rawValue.x, rawValue.y);

#

ScreenPointToRay expects a screen space position - which is exactly what an input action bound to mouse position will give you

#

Actually - here's another question - which I asked earlier but you didn't answer:
What exactly is the Aim action bound to?

#

Is it mouse/pointer position? Or something else?

plucky copper
wintry quarry
plucky copper
plucky copper
alpine quarry
#

my character keeps bouncing of of the floor if I freeze Y it still does it only turning of gravity fixes it but i will need it later

rich adder
alpine quarry
rich adder
rich adder
alpine quarry
rich adder
alpine quarry
rich adder
alpine quarry
#

I did its falling through the floor

rich adder
alpine quarry
#

I did now same issue

#

is there a vc in this so i can stream

rich adder
#

you have Y frozen it shouldn't even be falling..

alpine quarry
#

had it frozen

#

if I freeze it it still bounces

#

its not on frozen anymore

wintry quarry
#

You would only do new Vector3(x, 0, y) when you're for example swizzling joystick input into a local space game world direction

rich adder
alpine quarry
#

I know thats exactly why Im asking for help I dont have one

rich adder
stuck parrot
#

hey, does anyone have any idea why my character glitches like this? this doesnt happen every time i hit play, sometimes it stays stable but it does happen often

rich adder
stuck parrot
#

this is my first time using cinemachine tho so I dont know if I got all the settings right

rich adder
#

you'd have the show the component and which settings are set on both that and cinemachine brain,
also show movement code

stuck parrot
rich adder
#

eg Update and FixedUpdate perform at different rates

#

if you're using the rigidbody, it only moves on physics ticks

stuck parrot
rich adder
#

@stuck parrot out of curiousity where in code are you moving the character and which setting you have in cinemachine brain under update mode

stuck parrot
#

I just created a freelook camera and didnt do much with the settings because I dont understand cinemachine jet

versed sapphire
#

I am trying to activate a bool with a script, and it does not want to communicate with each other. I use Unity, the game is 3d

night raptor
versed sapphire
#

Do I send a photo or just the text

rich adder
radiant voidBOT
versed sapphire
rich adder
versed sapphire
#

it is not activating the bool or interacting with the animator

rich adder
versed sapphire
#

They are

rich adder
versed sapphire
#

I debugged it

rich adder
versed sapphire
#

Like it is triggering the debug log but doesn’t change the bool that I set in the animator

rich adder
#

I mean yeah the line is commented out

#

how would it change animator bool if its commented out
(and also written incorrectly)

versed sapphire
#

Do you mean the setbool line it didn’t work so I commented it out it gave me an error that said I had no overload

rich adder
#

you're trying to pass 1 argument which that function doesn't have

#

and it would not make sense to have 1 param anyway

broken nest
#

Hey, i've got an error saying i already have a definition for "theScriptName". How do I remove one?

slender nymph
wintry quarry
#

You may have duplicated the whole script

broken nest
#

there are in seperate project

wintry quarry
#

Doubtful

#

Show us?

broken nest
#

I'm gonna see what changing the name does

astral bronze
#

my tic tac toew game!

wintry quarry
#

Yikes

slender nymph
wintry quarry
#

Nobody should share or run a random .exe file in discord

broken nest
#

Hey changing the name of the script did the trick

wintry quarry
modern lodge
earnest wind
# astral bronze

please dont run this for anyone reading this, dont even download it

#

even if an antivirus says that its not a virus, its not a 100% confidence

#

there are evasion viruses and zero day ones so be careful

long jacinth
#

hello im having problem where my cursor is not visible even when i didnt ask it to do that and the camera has this weird jitter it kind of snaps weirdly

night raptor
long jacinth
# night raptor You need to provide all relevant code. The ones responsible for handling the cur...
using System.Collections.Generic;
using UnityEngine;

public class CameraMovement : MonoBehaviour
{
    public float sensX;
    public float sensY;

    public Transform orientation;

    float xRotation;
    float yRotation;
    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        //Cursor.visible = false;
    }

    // Update is called once per frame
        void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * Time.deltaTime * sensX;
        float mouseY = Input.GetAxis("Mouse Y") * Time.deltaTime * sensY;   

        yRotation += mouseX;
        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
        orientation.rotation = Quaternion.Euler(0, yRotation, 0);
    }
}
night raptor
#

Also from the documentation:

A locked cursor is positioned in the center of the view and cannot be moved. The cursor is invisible in this state, regardless of the value of Cursor.visible.

#

In case you are wondering, yes your tutorial (or AI perhaps) might have told you to multiply by deltaTime there but that is wrong. Some popular tutorials make that mistake. Again, this only applies for mouse axes, deltaTime should be used for most other things

long jacinth
#

only problem is my lag spikes idk what made my laptop so slow :/

#

but how do i know if what other stuff is frame dependant in unity

night raptor
long jacinth