#💻┃code-beginner

1 messages · Page 705 of 1

rich adder
#

its set false in 2 places, 1 is initializer .. If it aint being set false, maybe it aint being set to true at all

naive pawn
#

have you tried debugging outside the if

thorn abyss
rich adder
#

Debug.Log the collision first

rich adder
#

you know your setup better than me, you have to explain what that means in this context

red igloo
rich adder
#

and where you place script

rich adder
# red igloo

this script is not on any object with the collider

#

also curious, y does the wall have a dynamic RB

thorn abyss
rich adder
red igloo
thorn abyss
#

Ye

rich adder
#

if parent had rigidbody itself for example it will work cause its all 1 rb

#

why not put it on the player and check for walls that are destructable Tag or something

red igloo
snow wharf
#

Hey yall. So I wanted to get started with Unity. But i always get this Error: Could not find Unity Package Manager local server application at [D:/Unity/6000.1.14f1/Editor/Data/Resources/PackageManager/Server/UnityPackageManager.exe]. Missing files could be the result of an antivirus action or a corrupt Unity installation.

Click on Retry to relaunch Unity and reopen your project.

Click on Diagnose to launch the Unity Package Manager Diagnostics tool.

Can anyone help me? I deinstalled it multiple times now and i deactivated the antivirus i had on. Im lost....

thorn abyss
# rich adder now its just a matter of further drilling down where its going wrong

Actually no talk did get set to true. I put in the update function if(player.talk){ debug.log("should display") } and it did show but not every frame after talk should've been set to true. i also put if (!player.talk){debug.log("not displaying"), which i commented as it is showing every frame and only if i commented it i could see "should display" being printed

rich adder
thorn abyss
#

(Not "no talk did get set to true", i meant "actually, no.")

rich adder
#

huh I don't get it

thorn abyss
#

Should i send a video or sm

#

if (player.talk)
{
Debug.Log("should display");
dialogueBG.style.display = DisplayStyle.Flex;

        }
        else
        {
            Debug.Log("not displaying");
            dialogueBG.style.display = DisplayStyle.None;
           
        }
#

this is what i put in the update function

rich adder
thorn abyss
#

and "not displaying" got printed out constantly every frame. but "should display" also get prints everytime only when i hit 'x' which triggers the dialogue

#

so this possibly means that after talk gets set to true it gets set to false straight after

#

i think

thorn abyss
#

now ill dive in more

#

wait no

#

but it doesnt make sense

#

the whole dialogue is being called normally

rich adder
#

the machine never lies

wintry quarry
rich adder
#

if you have something like
if(inputKey) talk = true
else
talk = false

Guess what, its being set right away back to false

thorn abyss
#

oh

#

ill checkl

wintry quarry
#

I mean it's right there

thorn abyss
#

Why does it says all compiler error have to be fixed to enter play mode when there are no compiler errors and i saved it

rich adder
acoustic belfry
#

hi, for a weird reason when i try to use my Codex, this message appears

MissingReferenceException: The object of type 'UnityEngine.RectTransform' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.

thorn abyss
#

i definately changed everything that refernce the deleted die() function

#

and saved it

rich adder
thorn abyss
#

oops

#

guess what line 53 is blank

#

oh wait thats the wrong script

naive pawn
#

trigger and manager should probably be serialized references btw

thorn abyss
#

what do you mean

acoustic belfry
naive pawn
thorn abyss
#

yes?

naive pawn
#

they aren't assigned in the inspector in the code you showed

#

i don't see the declaration, so can't say if they're serialized fields already

thorn abyss
#

oh i used get component

#

ye i assigned it thx

naive pawn
#

yes, im saying they should be serialized references instead

thorn abyss
#

oh may i ask why

naive pawn
#

Find is somewhat fragile, it uses magic strings

#

you should avoid it (and magic strings in general) if possible

thorn abyss
#

that makes sense thx for the advice

sour fulcrum
#

also intensive, imagine making a list of everyone in the world and asking each one if they are your neighbor

thorn abyss
#

oh lol ok

#

why does this happen

sour fulcrum
#

how would we know

naive pawn
#

you don't need the GetComponent in Start

thorn abyss
#

but why does it work for manager and not trigger?

naive pawn
#

no clue, you shared your code in an ass format

thorn abyss
#

true my bad

naive pawn
#

im not gonna look through that grainy screenshot any more than i have to lmao

rich adder
#

trigger and manager were probably declared as GameObject instead of their respective types

#

ops my stupid discord just updated didnt see chris already said it

thorn abyss
#

What does cs0104 'debug' is an ambiguous reference between 'unity engine' and 'system.diagnostic'

grand snow
rich adder
#

shit just realized the same question was posted

grand snow
acoustic belfry
#

sorry

#

but yeah

thorn abyss
acoustic belfry
rich adder
#

alr well yeah keep coding questions in code channel

acoustic belfry
#

yep im trying to do that rn, but in case it may dont work

rich adder
acoustic belfry
#

now im realizing, is when close the Codex when this happens

grand snow
acoustic belfry
#

didn you said to make it less redundant?

thorn abyss
rich adder
acoustic belfry
#

ok

rich adder
#

redudant code just adds more noise to a script

acoustic belfry
#

also, worst part, is when i skip the error message, the game plays just fine

grand snow
rich adder
acoustic belfry
#

o h

grand snow
#

If the error is only when you close/destroy the UI it may not actually break anything

rich adder
#

even if it seems fine you shouldn't have that because you have a flaw in the design

grand snow
#

er I dont think thats fair to state rn

#

It could be easily fixable and not really matter

acoustic belfry
#

also something i found now, is that.....saved entries persists.. BETWEEN TESTS

i mean, i made it to unlock an entry for test how would look...and now despite i deleted all ways to unlock it, remains unlocked

rich adder
#

its an easy fix, just make the design better.. Dont access things after they got destroyed lol

acoustic belfry
#

m a y b e i s r e l a t e d ?

grand snow
acoustic belfry
#

thats the fun and creepy part, i dont do that yet

#

only thing with memory is the DDOL object

grand snow
#

It may be you are modifying a scriptable object which will keep changes post play

#

which is bad and you should stop

rich adder
#

DDOL shouldnt run between runs.. you got something else goin on

acoustic belfry
#

modifing an scriptable object?

#

i only have one

grand snow
#

remember the "wiki assets" you made a few days ago?

acoustic belfry
#

and i only use it for the asset

rich adder
#

cryptic

acoustic belfry
#

literally everything i did, was following for the tutorial for making Ui's

grand snow
#

If you are sure you dont modify them thats good

rich adder
#

did you store objects in the SO ?

#

cause if you did, don't lol or at least clean them up after

acoustic belfry
#

i use the SO like a kind of plain for the buttons

#

i mean

#

this is the so script

thorn abyss
#

is it possible to assign a uidocument in the inspector window? because it keeps saying reference is null

acoustic belfry
#

[CreateAssetMenu(fileName = "CassielDictando", menuName = "Cassiel/Journal Entry")]
public class CassielEntrySO : ScriptableObject
{
    public Sprite Foto;
    public string Nombre;
    public string descripcion;
    public int categoria;
}
rich adder
acoustic belfry
rich adder
#

oh as long as you dont store things from scene in it you're fine

grand snow
#

what are you on about

acoustic belfry
#

wat

grand snow
#

nav, not you

rich adder
#

huh? wdym ?

grand snow
#

the last issue was data saving between sessions but we can see the scriptable object type doesnt hold this data

#

I presumed it could be the cause but thats not the case

rich adder
#

I literally just saw what their SO does lol I saw SO mentioned and asked if they stored scene items not sure what was confusing

#

the only UI items they mentioned being destroyed was buttons, I'm still putting my money on they getting accessed after being destroyed, perhaps living as null in some collection. No idea as half this code looks AI

grand snow
#

I see starchild has asked about a topic that began yesterday elsewhere. much effort was spent trying to help them with some ui code but different people saying different things each day doesnt help either side

acoustic belfry
#

ok

rich adder
#

I'm answering without prior context so yeah maybe they should have a thread if they are asking about the same system someone else on this discord suggested to do

#

I just saw the "RectTransform was destroyed while you trying to access it " error and suggested where to look into

grand snow
#

yea missing context confuses all sides 😆

acoustic belfry
#

;-;

#

sorry

grand snow
#

Its okay, when we don't know its hard to ask the right things or know what to try

thorn abyss
#

Actually, now the dialogue panel just shows up straight away but "not displaying" is still getting printed

waxen glacier
#

So i've added a bunch of stuff to my character controller script since this morning, and although it's not as bad as before, i'm still noticing some slight inconsistency with the height at which the capsule jumps by looking at the position on the Y axis. It's not outrageous but i'd rather eliminate if possible. Here's the code : https://paste.ofcode.org/NpqFX9xzuqyBh2uVyvdd4P

#

Not sure what mistake I made this time

urban elk
#

Hello, are there any websites for codes in C# pls ?

west stag
#
start:
var enumerator = map.GetEnumerator();

int idx = 0;
foreach(var kvp in map)
                   
{
    if (math.distance(pos, enumerator.Current.Value) < viewDistance)
    {
        if(idx > results.Length)
        {
            viewDistance = (ushort)(viewDistance / 2);
            goto start;
        }
        results[idx] = enumerator.Current.Key;
        idx++;
    }
}

Is using goto bad? that looks a lot cleaner to me than

// Retry loop for adaptive shrinking of viewDistance for this cell
            int attempts = 0;
            const int maxAttempts = 8;
            bool cellDone = false;

            while (!cellDone && attempts < maxAttempts && viewDistSq > 0f)
            {
                int idx = 0;
                int count = 0;

                foreach (var kvp in map) // assume kvp.Key is the result key, kvp.Value is its position (Vector3/float3)
                {
                    // compute squared distance
                    Vector3 diff = pos - kvp.Value;
                    float dSq = Vector3.Dot(diff, diff);
                    if (dSq < viewDistSq)
                    {
                        count++;
                        if (idx < results.Length)
                        {
                            results[idx++] = kvp.Key;
                        }

                        if (count > results.Length)
                            break; // overflow detected early
                    }
                }

                if (count <= results.Length)
                {
                    // fits; done with this cell
                    cellDone = true;
                }
                else
                {
                    // too many: shrink and retry
                    attempts++;
                    viewDistSq = (viewDistSq / 4f); // equivalent to halving viewDistance: (viewDistance/2)^2 = viewDistance^2/4
                }
            }

naive pawn
urban elk
naive pawn
west stag
#

the end result is the same

naive pawn
#

definitely not, kvp isn't even used in the first block

west stag
#

all that extra work is required to avoid the goto

west stag
#

is kvp.key

naive pawn
#

nope, separate iterators

west stag
#

nope

naive pawn
#

the foreach structure gets its own enumerator

west stag
#

oh my mistake

#

I sent the wrong code block

#
var enumerator = map.GetEnumerator();
start:
int idx = 0;
while (enumerator.MoveNext())
{
    if (math.distance(pos, enumerator.Current.Value) < viewDistance)
    {
        if(idx > results.Length)
        {
            viewDistance = (ushort)(viewDistance / 2);
            goto start;
        }
        results[idx] = enumerator.Current.Key;
        idx++;
    }
}
naive pawn
#
+ while (true) {
      var enumerator = map.GetEnumerator();

      int idx = 0;
      foreach(var kvp in map)
      {
          if (math.distance(pos, enumerator.Current.Value) < viewDistance)
          {
              if(idx > results.Length)
              {
                  viewDistance = (ushort)(viewDistance / 2);
-                 goto start;
+                 break;
              }
              results[idx] = enumerator.Current.Key;
              idx++;
          }
      }
+  }
```this is all you need to remove the `goto` from the first codeblock
west stag
#

wait what

#

let me check that lol

naive pawn
#

(it seems like faulty logic - like this was a half-finished version - though, so it probably won't work. im just using that first codeblock to demonstrate)

west stag
#

i have went a long time assuming break breaks out of all current loops

naive pawn
#

nah, just the current one

#

some languages even have labelled breaks (and continues) for finer control, unfortunately c# is not one of them

grand snow
#

we dont talk about goto 🎵

west stag
#

right now i have a loop, inside of a loop, with two more loops inside of that.

#

yuck

#
 NativeParallelHashMap<Cell, NativeParallelHashMap<ushort, float3>> entries;





 public bool QueryPosition(Vector3 pos, ushort viewDistance, ref ushort[] results)
 {
     var cell = Cell.FromVector3(pos, worldData.cellSize);
     bool foundAny = false;

     int baseX = cell.x;
     int baseZ = cell.z;

     for (short dz = -1; dz <= 1; dz++)
     {
         for (short dx = -1; dx <= 1; dx++)
         {
             var neighbor = new Cell
             {
                 x = (short)(baseX + dx),
                 z = (short)(baseZ + dz)
             };

             if (!entries.TryGetValue(neighbor, out var map))
                 continue;

             
             var enumerator = map.GetEnumerator();
             while (true)
             {
              
                 int idx = 0;
                 while(enumerator.MoveNext())
                 {
                     if (math.distance(pos, enumerator.Current.Value) < viewDistance)
                     {
                         if (idx > results.Length)
                         {
                             viewDistance = (ushort)(viewDistance / 2);
                             break;
                         }
                         results[idx] = enumerator.Current.Key;
                         idx++;
                         foundAny = true;
                     }
                 }
             }

            
         }
     }

     return foundAny;
 }

any suggestions to clean this up?

grand snow
#

why is the enumerator being itterated without foreach?

#

and im sure you know while true is not always a good idea

#

this also seems to not be beginner code

west stag
#

sure it is

grand snow
#

its really not 😆

west stag
#

ok noted ill use foreach

#

but that really not going to clean it up any. Its code for a spatial hash

hallow adder
#

it's definitely not a good idea in this case since there's no exit from the outer while loop, this code will loop infinitely

west stag
#

What the code is doing is looping the collection and returning any that are in neighboring cells and within "view distance" and if there are more then the length of the results array reducing the view distance and starting over

hallow adder
#

why use the native parallel hash map? I assume this is going to be jobified at some point so you might as well do that now

west stag
#

I will if the benchmarks show this as performance critical code, but in the network update loop I am using this collection inside of a job

rugged beacon
#

whats the different between:

    public static IEnumerator SaveCoroutine()
    {
        var task = Task.Run(() => Save());
        yield return task;
    }
``` and
```cs
yield return new WaitUntil(() => task.IsCompleted);
grand snow
#

wtf is that first one

hallow adder
#

both of those look like landmines for the unsuspecting

grand snow
#

wrong channel

wintry quarry
#

They're more or less the same the second one just allocates a WaitUntil

rugged beacon
#

bet thanks

grand snow
chrome fern
#

How many times should Random.InitState((int)DateTime.Now.Ticks); be used?

wintry quarry
#

Idk can you actually yield return a Task?

desert sequoia
wintry quarry
#

I'm not sure yet can

chrome fern
#

It's for a roguelike.

grand snow
#

did you read the rules smh

wintry quarry
west stag
rugged beacon
west stag
#

dude says hi and you''re in here complaining

wintry quarry
#

You should check

wintry quarry
#

Because you're not doing anything after the yield

chrome fern
rugged beacon
wintry quarry
#

Generally rogue likes aim to be deterministic after the initial loading/seeding process

rugged beacon
grand snow
#

Task.run uses threading so you should just call Save() normally

wintry quarry
rugged beacon
#

yea

rugged beacon
grand snow
#

best change it then

wintry quarry
#

You can read and write files with UnityWebRequest funnily enough

#

That'd be the most Unity native way to do it

naive pawn
grand snow
west stag
naive pawn
chrome fern
west stag
naive pawn
west stag
#

starting big and going smaller would only lead to more iterations if there were a ton of items in the same area which isn't going to happen often

naive pawn
#

actually wait - is cells to values 1:1?

west stag
#

its a spatial hash its a cell with a list of values basically

#

NativeParallelHashMap<Cell, NativeParallelHashMap<ushort, float3>> entries;

naive pawn
#

ah i see, i misunderstood

west stag
#

essentially i am getting the current cell of the camera, looping through that cell and 8 surrounding it then looping through each item in each cell

naive pawn
#

another option (more straightforward but more work) would be to get all the neighbors' values and sort and get a range, but that might be significantly more work depending on the size of the result list and amount of items

west stag
naive pawn
#

(could be made better by sorting each area to get only the result count of items and then basically doing a merge sort)

naive pawn
west stag
#

i should probably just job it and sort them tho tbh

neon forum
#

I'm pulling my hair out with this error here regarding my code reading an asset and taking that asset and modifying the button prefab into that card.
It's able to read the card in the initial script, but when I attempt to do a setup function in another script it fails to read the cardName

flat socket
#

hi i am using unity first time and can someone help me with loading textures to my city becasue everythingis purple?

wintry quarry
#

!code

eternal falconBOT
wintry quarry
#

Since you're reading it and never assigning it

#

You're doing card = c after you've already been using the card variable

#

That needs to happen first

#

You do card.something 3 times before ever assigning it

neon forum
#

yeah that was it

#

I was calling card.Cardname not c.cardname

#

I'm passing c as the obj

#

not card

wintry quarry
#

I can see that

neon forum
#

that was the issue

native seal
#

could someone help me with my inventory system? I'm trying to make a system where saved or disposable inventories can be created at runtime. I have an abstract InventoryBase class and then concrete inventories inherit from that to add their own rules (food cant go into gear inventory, etc). I want a generic inventory UI controller but i'm having issues figuring out the best way for it to be able to hold any InventoryBase type. https://paste.mod.gg/molnyhyxtnyt/0

#

right now every inventory will be saved as the abstract type. I want a clean way to choose what type the UI controller should use, maybe like a dropdown in the inspector. However, I don't want to use serializereference since im creating random inventories at runtime

wintry quarry
#

Just a tagging system

#

The inventory slots can have whitelist or blacklist of tags

keen rampart
#

could anyone help me with this problem where my sound effect plays a second late when the player first moving, it like have a delay when the player first start moving. Im using the input system to detect the player input

north kiln
#

The timer starts at the interval and you check if it's under 0

#

So yeah, it'll have a step interval worth of delay

#

+whatever empty space is at the start of the audio

west stag
#

Is there somewhere I can go to find an in depth code review on something I think can be done better?

#

chatgpt only helps so much and tbh half the time its bad advice haha

wide rivet
#

how would I code it

#

is there any rescources I can learn from

#

can't really do it with no clues, I've never touched shaders before

raw tulip
#

How do nested prefabs work when working on a team project?

grand snow
# wide rivet how would I code it

Hmm perhaps with a noise tex/generated noise that scrolls on x and y
then using step restrict it to some parts of the noise to create the outline effect?

You probably need to start with something simpler to learn the basics

silk night
raw tulip
#

Should I duplicate said prefab and apply changes on my version, then we can combine em?

silk night
#

split the prefab into smaller chunks

#

if you have a current problem be more specific and its easier to help you

raw tulip
#

Is duplicating the prefab and working on my own version the move?

silk night
#

you will need to copy all the work of the other person afterwards

raw tulip
#

That's fine if it's safe

silk night
#

it is safe, but not easy as you cant really compare the two

#

you would have to manually go through each value

#

I would advise against it, if they just move a gameobject to the left, ok thats manageable, but anything beyond that and you will not find every change

keen rampart
keen rampart
north kiln
#

Create another timer to prevent that case

wide rivet
grand snow
#

It's mid way through a pathway so may be good to do it all

wide rivet
#

also does shaders affect UI?

I found some tutorials on how to do a 2d shockwave effect with shader graph and I was wondering if it would also do the uplift effect thing on the ui

visual fable
#

using the blend tree but my character isnt playing the animations despite it showing it on the blend tree, the bool saying moving is true it just stopped since i took the screen shot

#

although it is playing in here but not on the game scene

#

i dont understand why at all

#

haha figured it out

#

i had accidentally made a second animation layer and it messed it all up

fickle stump
#

Hey! A question, is there a way to check betwern a range of numbers?
What i want to do is to disable objects between 90 and -90 degrees rotation usually i check if objects are bigger or smaller than a certain number but for this situation i cant do that :<

#

(If the rotation is 90>= and =<-90) so i transition between 180 and -180

fickle stump
naive pawn
#

it can tell you how much 2 vectors are in the same direction

#

= 0 -> orthogonal (angle difference = 90°)
> 0 -> in the same direction (angle difference < 90°)
< 0 -> in opposite directions (angle difference > 90°)

#

and if they're normalized as direction vectors would be,
= 1 -> parallel (angle difference = 0°)
= -1 -> antiparallel (angle difference = 180°)

fickle stump
#

I see okay

#

I'll try to read more into this

#

Thank you!

fickle stump
#

Additionally: i'm currently having my objects snap to my mouse and hover them over a ground. However the object is halfway stuck in the other object, basically dragging object 1 through object 2. Is there a way to avoid this or os it better to adjust the pivot point?

floral garden
cinder mason
#

in unity I have the strangest bug, when I am making top down movement, when i click repeatedly my movement keeps going for a few seconds even when i stop. i have tried and the error still persistent: in a new unity scene, when using getaxis, getaxisraw, and getkey, in a build, and the input settings are still default (im using the old input system).

floral garden
naive pawn
eternal falconBOT
cinder mason
# naive pawn gonna have to show some !code about how you're moving the player

no its just the input. in my update function, regardless of whether its getaxis, getaxisraw, or just the actual inputs, it still does it
this stil does it in a blank unity scene

    Vector2 direction;
    void Update()
    {
        direction = Vector2.zero;
        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
            direction += Vector2.left;
        else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
            direction += Vector2.right;
        else if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
            direction += Vector2.up;
        else if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
            direction += Vector2.down;

        Debug.Log(direction + " | " + Input.GetButton("Horizontal"));
    }
grand snow
#

well this is not what you should do instead of GetAxis/GetAxisRaw

cinder mason
#

yeah but it happens regardless

grand snow
#

what does "direction" do? is it used to change velocity or add force?

cinder mason
#

no that wasnt the full movement script, that isnt the problem, its the actual input. it prints the right values until i start clicking, then my inputs get held for a bit when i release the directions.
the movement script is not the problem ebcause it happens here too in an empty unity scene, but in the original it is used to move position, with pos += direction * speed * deltatime

naive pawn
#

the movement script is not the problem because it happens in an empty scene
those 2 things just are not related

#

are you using a rigidbody, and what's the actual movement code

#

ah wait skipped a few words

#

this seems like maybe a hardware issue

#

have you tried a keyboard test site to see if that replicates the input weirdness you're seeing

lofty mirage
#

What is the good practice to move an enemy with rigidbody? (AddForce vs MovePosition vs velocity)

floral garden
#

Never touch velocity

lofty mirage
#

So both AddForce and MovePosition are decent methodologies?

floral garden
#

Addforce is what i am using

lofty mirage
#

I'm coding a Patrol function for dragonflys rn

#

top down view

floral garden
#

Oh

#

Then use a fsm + raycast + character controller

lofty mirage
#

fsm?

floral garden
#

Finished stats machine

lofty mirage
floral garden
#

Yeah like patrole, chasing, confus

lofty mirage
#

yeah okay

#

My plan was to first make the dragonflys move in the space

#

like random dir for 0.5sec, stop for 0.2s, look around swiftly for 0.5s, then speed up to some other random dir for 0.5s

#

then I had a raycast so that when they "look around", if raycast hits player (they see the player), they speed up to the player

#

Wdym by character controller? (for the enemy)

#

wdym by confus also?

fickle stump
#

When i' setting layers the one with higher prio will be rendered on top of the other?

floral garden
fickle stump
floral garden
#

May be i am wrong as i am still biginner too haha lul

lofty mirage
#

I have multiple layered grids

#

I changed the prio for rendering some on top of others

#

sometimes changing the order in the hierarchy in the viewport doesthe trick, but it's somewhat inconsistent in my experience; whereas layer ordering always works

fickle stump
#

I just dunno how to have more than 1 grid system active lol

floral garden
formal yacht
#

hii

floral garden
lofty mirage
#

For instance you can see in the Grid parent object that I have 4 tilemaps

#

it's not super optimized performance wise

#

but basically I have the shrooms on top of all (bonuses), then the walls/obstacles, then the walkable brown ground, then the dark green background

floral garden
#

Ugh

#

We cant do it in other ways ?

#

You can create a lot of layer and in layer you can also set priorities

#

Oh yeah i find it, you can do it with only one tilemap

naive pawn
naive pawn
lofty mirage
#

I agree that position is for teleportation

naive pawn
#

also CCs are kinda orthogonal to rigidbodies. you can use a rigidbody with a statemachine/casts just fine

lofty mirage
#

CCs?

naive pawn
floral garden
naive pawn
#

you can use velocities for both, you can use forces for both

#

they both work

floral garden
naive pawn
#

right don't parrot stuff without knowing why

#

there's no physical issue with setting velocities

floral garden
naive pawn
#

as the docs say - setting velocity can be jarring and unrealistic, but games don't have to be physically realistic

lofty mirage
#

Wdym casts? (statemachine I got is an enum with elems as states so that we manage the enemy through a switch statement (?))

naive pawn
#

raycasts & friends for detection

floral garden
naive pawn
#

not really

#

it's processed in FixedUpdate anyways

#

it's the time-dependant forces that need to be in FixedUpdate

lofty mirage
#

oh okay, first time I hear casts for raycasts

#

I have a bit of a hard time knowing when to Update() vs FixedUpdate() tbh

#

basically Update() for player input and FixedUpdate for consistent physics?

naive pawn
#

Update is per frame, FixedUpdate is per physics tick
consider whether the thing you're doing is frame-bound or physics-bound
for example, inputs are frame-bound, but continuous AddForce is physics-bound

floral garden
#

Btw, fixedupdate is not affected by frame lag

#

If i am correct

naive pawn
#

i mean, it kinda is

floral garden
#

Is it affected if your game lag ?

naive pawn
#

things happen in sequence, if the frame takes a long time then the physics tick will be delayed

#

it'll try to catch up by running multiple physics ticks per frame if the frame takes too long

#

but computer speed is finite so if the physics tick takes longer than the alloted time then it'll never really catch up

#

i don't know how that situation is handled actually. what im thinking of would lead to the game freezing completely thonk

floral garden
#

I think the fixedupdate is not executed with the update so if the update is freezed or slower than expected, the fixedupdate is still executed

naive pawn
#

no, computers can't do multiple things at once

#

the update has to finish before the fixedupdate can happen

floral garden
#

Hmm hardware limits

#

Need to do some research lmao

floral garden
#

My little brain can’t understand

#

Oh

#

Yeah you mean right , unity will catch the time update freezed then executing fixedupdate n time

#

Before going back to update

vital vault
#

how can i make sure that Start method of one object will be called before other?

vagrant mist
naive pawn
#

you should use awake instead yeah

#

SEO is per-scene and isn't easily analyzable - it could lead to unmaintainable code

vagrant mist
#

tru, that was just the first thing I found when googling the problem

floral garden
#

SEO?

#

is it a good ideas modifying the script execute order ?

fickle plume
floral garden
fickle plume
#

Or chain them properly so you know which goes after which

floral garden
#

hmm without context, it will be hard , the only one I want it being execute before all is the CoreManager that contain my customLogger.

fickle plume
#

So if you have a clear chain you should have managing script activating them through reference and not have several scripts running awake

floral garden
#

you mean, I create a script that will execute all other script it self in the order i want and leaving empty all awake then create a function Init() to init the script ?

fickle plume
#

Something like that yes

strong wren
#

Switching to explicit initialization order might be better longer term, but it's fine to use the execution order system. DefaultExecutionOrder class attribute is another way to set the execution order.

floral garden
#

oh my, I need to change a lot of thing then

strong wren
#

I would worry more about it with your gameplay systems. Logger needing to have earlier initialization is probably not very surprising.

rancid tinsel
#

is it okay to make OnApplicationQuit static?

grand snow
#

It won't be magically called this way

#

But there should be an event you can sub to

polar acorn
rancid tinsel
polar acorn
#

Those are mutually exclusive options

floral garden
#

I finally finish to applying Fogsight ideas

#

lmao

fickle plume
# floral garden I finally finish to applying Fogsight ideas

Keeping naturally flowing call chain will help to instantly see how everything runs in what order. It's also perfectly fine taking advantage of rigid overrides for call order, but it's better to do when you have established structure that you know won't change. Or for tools. TextMeshPro for example overrides theirs.

spiral narwhal
#

text.fontStyle = FontStyles.Italic;

How do I specify both FontStyles.Italic AND FontStyles.Uppercase?
I think it's not an enum flag. I'd rather not use rich text tags for this

floral garden
fickle plume
#

#⚛️┃physics question. But generally you use joints/hinges to have multiple rigidbodies be part of one system.

floral garden
#

oh I know it haha but forget the name pika_mdr isn't they trace the trajectory then if it hit something then it will replace the object at the collider position (something like that)

spiral narwhal
vital vault
#

how to generate perlin noise sprite really quick? like i need at least 60 fps

west stag
#

job system

west stag
# vital vault how to generate perlin noise sprite really quick? like i need at least 60 fps

There prolly a much better way to do it but chatgpt looks to have given you a pretty good starting point

    [BurstCompile]
    private struct GeneratePerlinJob : IJobParallelFor
    {
        public int width;
        public int height;
        public float scale;
        public float offsetX;
        public float offsetY;

        // flattened result: index = y * width + x
        public NativeArray<float> result;

        public void Execute(int index)
        {
            int x = index % width;
            int y = index / width;

            float fx = (x + offsetX) * scale;
            float fy = (y + offsetY) * scale;

            float2 sample = new float2(fx, fy);
            float n = noise.cnoise(sample); // returns in [-1,1]
            n = (n + 1f) * 0.5f; // normalize to [0,1]
            result[index] = n;
        }
    }
vital vault
west stag
red igloo
west stag
vital vault
floral garden
#

It cost is equal to your screen size like weight x height so qhd will cost more than hd. How about pre generate sprite then load sprite ? Did it cost more to load a sprite than creating a sprite ?

red igloo
#

I dont know whats wrong with it seems okay to me

west stag
west stag
floral garden
#

Ah null ref

#

Link your vscose with unity

#

Then go in debug

hexed terrace
# red igloo

your mainplayer prefab must not have an InputActionReference assigned

west stag
hexed terrace
#

In the prefab that gets spawned?

red igloo
hexed terrace
# red igloo

You need to look at the new player clone tht is spawned, not the same obejct that was already setup..

red igloo
#

your right

#

need to get rid of the clone lol

#

I see thanks!

hexed terrace
#

because all those things look like you've assigned them in the scene, so are only valid for that instance and **NOT **the prefab

naive pawn
#

that sounds like a seizure hazard - and really uncomfortable otherwise

vital sparrow
#

Hello, I'm a training manager for ASTM. I've been bumbling around unity trying to animate and build a materials test. I have the project done, except I can't get any usable performance on Web. I want to prove, unity could be a good option to educate. Can anyone help me get my single scene working?

trim burrow
#

Hey! I'm new to unity and I made a script where the gun will look towards my mouse cursor, but I encountered a problem, at certain positions the gun starts sliding. I assume this has to do with if the collider is in a slope. How could i fix this issue?

grand snow
hexed terrace
grand snow
#

oh derp it is

vital vault
#

but i mean for it to look like in fnaf 1

naive pawn
#

camera static?

vital vault
#

and yes, i know that in fnaf 1 it was just 8 sprites looping

vital vault
#

but this effect is also in menu

naive pawn
#

isn't perlin noise meant to be like, a gradient

vital vault
naive pawn
#

that's very different to static

vital vault
naive pawn
# vital vault gradient?

it has random hot spots and cool spots but there's a gradient between then instead of jarring transition, no?

vital vault
#

but it could be octave noise

grand snow
naive pawn
#

because a static signal is more noisy than perlin noise, i guess? im probably misusing terms

naive pawn
#

"noise" just means a space with random values

#

camera static would probably more accurately be white noise

vital vault
#

this is from original fanf dump that i made

#

strange

naive pawn
#

perlin noise is interpolated

#

perlin noise

#

white noise

naive pawn
#

maybe noise biased to low values and stretched to give the horizontal smearing lol

zenith cypress
#

Could probably take white noise, expand the dark areas, then stretch it to get the fnaf effect

vital vault
naive pawn
#

just a few looping images would be easier and way more performant than generating it all at runtime tbh

vital vault
vital vault
hexed terrace
#

Pre-make some, save them, use them to loop over.

It's really not worth the performance hit to do it realtime

naive pawn
#

a naive but probably very inefficient way would be to just generate a random value for each pixel/region

hollow slate
#

perlin-noise isn't that expensive in 2D. You could procedually do that no-prob no?

naive pawn
#

might even give some bias towards darker values lol

vital vault
hexed terrace
naive pawn
vital vault
naive pawn
#

in the absence of a signal, noise is interpreted as the signal

vital vault
#

to make realistic tv noise you need to make an algorithm that will decode video from random values

spiral narwhal
#

Is it okay to use PlayerPrefs for settings or should I use a file

naive pawn
#

it was all 1:1

vital vault
hexed terrace
#

i wouldn't say definetly, but it's ok yeah

naive pawn
ashen salmon
#

How can I turn the selected graphic into a 2d touchscreen mesh for cancelling out point touches?

#

it's leaning because the game is half down orthographic

hollow slate
hexed terrace
#

you fix the issue by finding out why it's moving, then.. stop doing that

trim burrow
# hexed terrace where's your code?
using UnityEngine;
using UnityEngine.InputSystem;

public class Movement : MonoBehaviour
{

    Keyboard keyboard;
    private Camera cam;
    [SerializeField] private float movementSpeed = 1f;
    [SerializeField] private Rigidbody2D rb;
    private Vector2 movementDirection;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        keyboard = Keyboard.current;
        rb = GetComponent<Rigidbody2D>();
        cam = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {
        if (keyboard.dKey.isPressed)
        {
            rb.linearVelocityX = movementSpeed;
        }
        else if (keyboard.aKey.isPressed)
        {
            rb.linearVelocityX = movementSpeed * -1;
        }
        else
        {
            rb.linearVelocityX = 0;
        }

        Vector3 mousePos = (Vector2)cam.ScreenToWorldPoint(Input.mousePosition);
        float angleRad = Mathf.Atan2(mousePos.y - transform.position.y, mousePos.x - transform.position.x);
        float angleDeg = (180 / Mathf.PI) * angleRad;

        transform.rotation = Quaternion.Euler(0f, 0f, angleDeg);
        Debug.DrawLine(transform.position, mousePos, Color.darkRed, Time.deltaTime);

    }

(its probably highly uneffective ik) But i dont think it has to do with my code and more so with the engine itself

#

(I was not using the movment keybinds in that video)

hexed terrace
#

I would assume then, that your collider is a box? and that rotates with the gun.. so you're then on a corner of it perhaps, while it tries to use gravity to pull it back flat and keep the angle you put in the code

trim burrow
hexed terrace
#

depends on how you want it to act

#

easiest solution is to disable graivty when the buttons aren't pressed?
Or freeze movement on the rb

ashen salmon
#

There might be a suitable mesh collider maybe

trim burrow
ashen salmon
#

I presented my game to my nephew and it's the first time he's seen a game I wrote

#

My newphew found that annoying, my brother was disappointed touch happen off the game screen

vital vault
#

how can i perform something on first frame? not on load

west stag
cosmic quail
vital vault
#

because if i start scene preload, it will preload when i preload first one

vagrant mist
#

Start is performed on First valid frame when the object is enabled

vital vault
cosmic quail
naive pawn
#

don't think that's particularly helpful

naive pawn
vital vault
#

the point is to make it seamless

naive pawn
#

ah, gotcha

#

Awake is called when the GO is loaded and is active
Start is called when the GO is loaded & active, and the component is enabled

with the async scene load, the GO won't be active until the scene fully loads

vagrant mist
naive pawn
#

just !ask , don't ping specific people for help

eternal falconBOT
naive pawn
vagrant mist
#

[In Unity2D] I have an bulletObject that is being fired into an enemyObject. Both have colliders and a Rigidbody2D. On the bulletObject, I have an OnCollisionEnter2D function that destroys the bullet when it hits the enemyObject. The enemyObject has a basic chase script that uses MoveTowards() to track my playerObject.

Before shooting a bullet, the pathfinding works like it should, but when the bullet hits the enemy, the enemy stops moving towards the player and kind of just spazzes out. Is it because of Destroy(bulletObject) adding a force to the enemy that could be messing with its movement or could there be something else I'm missing?

slender nymph
#

you'd have to show relevant !code

eternal falconBOT
vagrant mist
#

Bullet's Script

public class BulletScript : MonoBehaviour
{
    private Vector3 mousePos;
    private Camera mainCam;
    private Rigidbody2D rb;
    public float bulletForce;
    void Start()
    {
        mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
        rb = GetComponent<Rigidbody2D>();
        mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
        Vector3 direction = mousePos - transform.position;

        Vector3 rotation = transform.position - mousePos;
        rb.linearVelocity = new Vector2 (direction.x, direction.y).normalized * bulletForce;
        float rotZ = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0f, 0f, rotZ + 180);
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Destroy(gameObject);
    }
}
naive pawn
#

MovePosition doesn't obey collisions, btw. i don't remember if it detects collisions..

floral garden
naive pawn
#

wait that's not what you said you were using

vagrant mist
#

Enemy pathfinding script

public class EnemyChase : MonoBehaviour
{
    public GameObject playerObject;
    public float enemySpeed;
    private float distance;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        distance = Vector2.Distance(transform.position, playerObject.transform.position);
        Vector2 direction = playerObject.transform.position - transform.position;
        direction.Normalize();
        float aimAngle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

        transform.position = Vector2.MoveTowards(this.transform.position, playerObject.transform.position, enemySpeed * Time.deltaTime);
        transform.rotation = Quaternion.Euler(Vector3.forward * aimAngle);
    }
}
vagrant mist
slender nymph
#

why are you moving the enemy object using the transform if it has a rigidbody on it?

#

also by moving it using the transform any forces applied by collisions and the like are completely overwritted so the rigidbody's velocity is irrelevant here

naive pawn
#

even the bullet, shouldn't that be rb.rotation = ...

slender nymph
#

eh, that line is in Start so it really isn't going to make a whole lot of difference there

#

although it would make it simpler since only a float would be required instead of a Vector3

vagrant mist
naive pawn
#

via the rigidbody

slender nymph
floral garden
vagrant mist
#

ah, so treat it similar to my player using rb.linearVelocity

vagrant mist
naive pawn
#

anything I want to move with a rigidbody should use it
yes
transform should be used for anything without it
not necessarily

#

the issue is that the rigidbody wants to control the transform, that's why you shouldn't modify the transform

#

that also applies to anything else that wants to control the transform

vagrant mist
#

you mentioned that MoveTowards would ignore collisions, should I still be find using that or is it not good practice for pathfinding

naive pawn
#

i misread, i thought you said MovePosition on the RB

#

MoveTowards is unrelated

#

but yeah with an rb you would probably have different math

final trellis
#

is there any way to have _rank and _type ( which are enums ) use the name rather than index

#

( using ToJson )

naive pawn
#

they aren't using index, they're just using the actual values
enums are named integers, the integer is easier to process

cosmic dagger
west stag
final trellis
#

that sounds like a lot 😭

west stag
#

its pretty simple and documented very well

cosmic dagger
#

It's simpler than you think . . .

#

Though, I do agree with @naive pawn; using the integer value is easier . . .

naive pawn
#

i mean you technically are asking to save something that's orthogonal to the actual value
i'd say it's a pretty reasonable amount of effort/complexity for that goal

west stag
#

its a lot easier than any hack you can make to make it work with unity built in json

final trellis
#

i think i might just have some comments in the default JSON file so users can know which number is which

west stag
#

brother its like 20 lines of code

#

chat gpt can probably even do it for you

naive pawn
#

and a whole new library

west stag
#

whats the struct

naive pawn
#

you're trying to impose technical debt on them lmao

red igloo
final trellis
#

i cast technical debt

#

i could also summon my new goat, the Dictionary

final trellis
#

some snippets i think

naive pawn
floral garden
final trellis
#

public static dictionaries are p cool i think

floral garden
final trellis
#

btw just making sure, you can write to private fields using JsonUtility if the field is serialized right?

west stag
#

btw

final trellis
#

bc i need this nightmare to be generated during runtime, hence the use of JSON in the first place

west stag
#
[JsonConverter(typeof(StringEnumConverter))]
    public Status CurrentStatus { get; set; }

this is all you gotta do to make it work if you use newtonsoft

naive pawn
naive pawn
final trellis
#

wdym by reflection btw

grand snow
#

you can also provide the string enum converter when serializing/deserializing (newtonsoft json)

west stag
grand snow
#

thats a shame, its probably the fastest one in c#

final trellis
naive pawn
west stag
naive pawn
#

the Type you get from typeof(SomeClass) is part of reflection, for example

red igloo
west stag
grand snow
naive pawn
naive pawn
west stag
final trellis
naive pawn
#

im saying newtonsoft is a new api to learn for ave

#

not a new library to add to the project or whatever - idk about that

naive pawn
#

yeah it probably should be a serialized reference

naive pawn
west stag
red igloo
#

been stuck on this shit for 2+ hours lmao

final trellis
naive pawn
naive pawn
#

yeah you should just use a serialized reference

west stag
red igloo
grand snow
#

wow that apple is old dont buy it!

floral garden
#

When do we use find function ? atwhatcost

naive pawn
#

generally you should not

#

there's always a better alternative, and usually that alternative is pretty easy and involves removing code

final trellis
#

its perfect for game jams when you cant be assed to code properly

floral garden
#

Hum that what i think too

grand snow
#

Its slow and requires an object to exist with a special name/tag
very unreliable

west stag
naive pawn
#

the alternatives are almost always easier than actually using Find

floral garden
grand snow
#

FindObjectOfType<>() is better as its using a component/object type but it shouldnt be used too much

#

you can find assets too

#

i dont recommend it

final trellis
west stag
floral garden
vital vault
#

Where unity saves my file that i wrote by just doing StreamWriter outputFile = new("savefile.json");?

floral garden
#

In the build hehe , idk 🤷

naive pawn
#

yeah no that just doesn't make sense

naive pawn
#

in the editor, iirc that just goes to the project root?

#

you should be able to just find it in file explorer

floral garden
vital vault
floral garden
#

How about you search with explorer ?

vital vault
floral garden
#

Ugh

vital vault
#

and savefile.json is just too common

floral garden
#

Maybe in your root unity file?

vital vault
#

i need for build

floral garden
#

Ah then i don’t know, maybe you need to specify the path for the build

string path = Path.Combine(Application.persistentDataPath, "savefile.json");
using StreamWriter writer = new(path);

elder hearth
#

Hi! so i want to get the name of the item im hovering over and setting a bool to true, but it the logic still runs even after im no longer hovering over the item

    public void Update()
    {
        //Methods

        Clicked();


        // Not long enough for a method




        // Only update MouseRayHit if something was actually hit
        if (RayMouseCast.LatestHit.collider != null)
        {
            MouseRayHit = RayMouseCast.LatestHit.collider.name;

            HoveringOverGun = MouseRayHit == "Cookie";
        }
        else
        {
            HoveringOverGun = false;
        }

    }
elder hearth
#

ray logic

public class RayMouseCast : MonoBehaviour
{


    public static RaycastHit2D LatestHit;

    void Update()
    {
        Vector2 mousePos = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
        RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector2.zero);

        if (hit.collider != null)
        {
            LatestHit = hit;
        }
        Debug.Log("Your ray hit" +  hit.collider);
    }


}
hexed terrace
#

all you're doing is checking for a collider, nothing else to say "display this things name"

#

You need to check if that game object is one you want to display a name for.

Either using a 'tag' (not very expandable)
or TryGetComponent<T>()

copper nebula
#

guys im getting into unity and creating games but i dont know where i could learn c#

hexed terrace
#

!learn 👇 -> and check the pinned msgs

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

copper nebula
#

thank you

ocean loom
#

how can i use a method from a different class in the current class im using?

rich adder
ocean loom
rich adder
ocean loom
rocky canyon
#

is the Shooting script on PlayerPos?

ocean loom
rich adder
ocean loom
rocky canyon
#

wait.. Detroy() if u destroy the gameobject does it continue running the rest of the code?

rich adder
#

yea marks it for deletion and gets removed on the next frame

ocean loom
#

well, the breakpoint like worked soo..

rocky canyon
rich adder
rich adder
ocean loom
ocean loom
rich adder
#

i have no idea where you put the breakpoint so I can just tells you if it hits a breakpoint it means that part reached

ocean loom
rocky canyon
#
    // put in OnCollision method to debug the results
    // im thinking the Component isn't where you're looking
    
    Debug.Log("Hit: " + collision.gameObject.name);
    Shooting myShootingScript;
    myShootingScript = PlayerPos.GetComponent<Shooting>();

    if(myShootingScript != null)
    {
      Debug.Log("We've gotten a Shooting script");
      myShootingScript.shootBlue();
    }
    else
    {
      Debug.Log("Couldn't get Shooting script component");
    }```
#

^ have u actually gotten the Shooting component u believe you have

ocean loom
trim burrow
#

How do i check the name of something my character collided with?

rocky canyon
#

oh its 2d

#

soo collision.gameObject.name

ocean loom
rich adder
ocean loom
rich adder
rocky canyon
#

^ yup.. couldnt agree more.. debug the entire flow ->

ocean loom
rocky canyon
#

heres what I would do for sanity: debug each step
// we collided
// heres what we collided with
// getting component from:
// did i get component or not? // running method
// method ran

hexed terrace
rocky canyon
#

^ i was also gonna say soemthing lik ethis.. since u already have ur PlayerPos cached.. and thats what ur apparently trying to get component from

ocean loom
#

sorry im quite new to coding im not sure i understand what expose a new field means

hexed terrace
#

public Shooting playerShooting; <- do that and assign it in the inspector

#

then just do playerShooting.shootBlue();

ocean loom
hexed terrace
#

As you don't need this to be dynamic, there is zero need to be doing a getcomponent every single time

rocky canyon
#

yup yup, at first i thought it was a mistake and they were trying to get the component from the collision object.. but since its not and being called from the same place everytime just make it a variable

ocean loom
#

like the gameobject isnt even being destroyed

rocky canyon
#

when you say "method" in that explanation are u refering to teh collision method or the method ur calling in the 2nd script?

ocean loom
#

i.e ShootBlue();

rocky canyon
#

lol. weird if u call the method it should run teh entire method

ocean loom
rocky canyon
#

it'll only call it once tho.. b/c OnCollisionEnter is only called on the frame of the collision

ocean loom
#

its being called after the collision

hexed terrace
#

1- You need to also be checking your console for errors.
2- Did you assign that in the inspector?

ocean loom
#

this one isnt being called

rich adder
#

did you check if it even reaches Destroy ?

#

cause it can hit that line with breakpooint you can just check if its null from breakpoint (you hover playershooting)

hexed terrace
#

I'm willing to bet there's a NRE

rocky canyon
#

aye, then ur error is probably there

rich adder
#

yeah most likely

rocky canyon
#

:headnodkitty:

ocean loom
rich adder
#

yeah so that line is throwing NRE

ocean loom
#

but it was reaching destroy before i put a breakpoint there

rocky canyon
#

forloop that junk

ocean loom
hexed terrace
#

while (notAnswered) { post; }

#

always use curly

ocean loom
#

i did check console and what should be assigned in the inspector?

polar acorn
hexed terrace
#

.. lol the component you want to call the method on, fs

#

rofl

ocean loom
ocean loom
rich adder
#

did you leave the breakpoint ? we cant see what you see lol

polar acorn
ocean loom
ocean loom
rich adder
# ocean loom yeah i left the breakpoint in

did you hover over PlayerShooting. part of the breakpoint.
if you did not hit Continue on the breakpoint hit Unity console would not print NRE for that line until you did. So You can just let the rest continue and check unity console after , hovering the PlayerShooting on that line would also tell you if its null

ocean loom
#

ive got to go for like 10-15 mins. if any of you are still online, ill try more things then.

#

thanks for the help though, much appreciated!

ocean loom
rich adder
rich adder
#

the one you made for PlayerShooting

ocean loom
rich adder
#

You declared it but never assigned it

#

computer has no idea which one to run it on

ocean loom
#

wait how do i assign it, nothing is showing up when i click it

rich adder
#

Imagine putting a label on a box, but never putting anything in the box

ocean loom
#

but, when i try and find the script, the inspector changes to its parent

#

is it supposed to be defined as a script

rich adder
ocean loom
#

instead of Shooting

#

cant drag the objecy

rich adder
#

why not, as long as it has the Shooting script on it

#

you have to describe / show whats happening , we dont have eyes on your pc lol

ocean loom
#

sorry

#

let me send a video

grand snow
#

inb4 the script not being added to the game object

ocean loom
grand snow
#

well well

ocean loom
#

is it supposed to be defined as "shooting" or "script"

rich adder
#

you're trying to put a scene object into a Prefab

#

you cannot do that

ocean loom
#

oh rightt, ok lemme try put the prefab into it

grand snow
#

oh good spot I didnt see it was a prefab asset

ocean loom
#

i cannot put prefab object either

rich adder
#

pleas use a proper screencapture next time, that motion made me almost fly off my chair

#

shareX or OBS

#

I think windws has built one too with snip thing or 🪟 + G

ocean loom
grand snow
#

it does (WIN shift S)

ocean loom
#

too large and i dont have nitro

rich adder
#

its like codepaste site but for vids

ocean loom
#

would you mind if i just screenshared to you?

ocean loom
rich adder
#

as long as it shows a CLEAR screencapture sure

ocean loom
rich adder
#

oh nahh thats too invloved lol

ocean loom
#

ok nevermind then

#

i cant put the prefab script in either

rich adder
#

explain a bit more what you want to do , in terms of what object does what and we can take it from there

#

no point of suggesting a fix if theres a better way to do it, you just have to explain what exactly is the end goal here

grand snow
#

^ yes read that

ocean loom
#

so basically, im shooting a bullet, and then the point in collision i want to set my portal transform to that collision.transform

grand snow
#

read that page because you lack critical understanding

rich adder
#

ohh so the bullet places a portal

ocean loom
rich adder
#

whatever spawns the bullet is already in the scene no ? so that link should help you pass the reference through when you spawn the bullet

ocean loom
#

do you want to see the code?

rich adder
#

did you look at the link sent?

#

Pass the component from the Player that has teleport script to the bullet when you spawn it

ocean loom
#

i tried to get the component from thr player

rich adder
ocean loom
#

originally, i had a raycast, and it would just place the portal on the collision of the raycast. But now, i want it to do that, after a bullet collision.

rich adder
# ocean loom yes

Pass the component from the Player that has teleport script to the bullet when you spawn it
//player
Shooting shootingScript
shoot()
var bullet = Instantiate(etc..
bullet.shootScript = shootingScript;

rocky canyon
#

^ just handing off the reference

rich adder
#

hmm prob better use a method so you can do something you need to
bullet.GetShootScript(shootingScript)

ocean loom
ocean loom
rich adder
#

its like telling someone "give me a tool from toolbox" and doesnt matter what the bring, it becomes that tool
var x = 5; tells the compiler: “You figure out what x should be,” and the compiler says, “That’s clearly an int.”

ocean loom
#

oh ok that makes sense

rich adder
#

Ideally here it would be BulletScript or whatever type you have on your bullet

#

never need to store prefabs as GameObject if you have script on it, store it as that specific type

#

"BluePortalBullet"

ocean loom
#

ok that makes sense

floral garden
rich adder
trim burrow
rich adder
#

lol you literally said the same thing

#

what type of character is your player ?

#

Rigidbody ? CC ? Custom ?

trim burrow
#

rigidbody2d

rich adder
#

OnCollisionEnter2D usually

#

or you can use a physics cast like ray etc

trim burrow
#

Yeah but i want a codition to happen if the name of the object is something specific

rich adder
trim burrow
rich adder
#

mhm

trim burrow
#

Alright ill try to figure that out thanks

rich adder
#
{ // has script }
else
{//its not what we want}```
https://docs.unity3d.com/ScriptReference/Collision2D-collider.html
https://docs.unity3d.com/ScriptReference/Component.TryGetComponent.html
#

you can also search Up parent or children if collider is not the one with script but parent/child does, but that involves multiple lines with
GetComponentInParent / GetComponentInChildren

ember tangle
#

Can Unity's JSON serialization work with 2d arrays?

rich adder
#

wrap it in class/struct

#

use json.net tbh. its better, also supports dictionaries and others

cedar prairie
#

dude what the fuck is going on here

rocky canyon
#

negative scales 0 scales fckin with the rendering

cedar prairie
#

how would i fix it and or find the things in the negative

#

okay nows its just gone?

#

litreally changed fuck all

#

thanks btw haha

grand snow
#

frame debugger can be used to figure out stuff like this (if you have some base knowledge to use it)

rich adder
hearty glade
#

Hi folks! I have 2 phones: phone 1 has higher specs than phone 2, but the sprites are twitching really bad on phone 1, and really smooth on phone 2.

teal viper
rocky canyon
#

it seems to be something to do with dividing by zero.. or bad values for the shader/materials

rich adder
hearty glade
rich adder
#

iirc 60 fps will not do anything on mobile, i believe unity caps it at 30

rocky canyon
rich adder
#

in what way is it twiching btw? I do see a Tween but that usually accounts for delta iirc

cedar prairie
#

thank you all for the help! ill be sure to not do that lol

rocky canyon
#

ya.. flashbanged me first time it happened

cedar prairie
#

honestly lol

hearty glade
fickle stump
#

IDK if that's a question thats considered beginner but:
Is there a way to combine scriptable object with localisation strings?
My idea is to have my scriptable object with a description of my object, depending on what language i want to print that language. Somebody know how/if i can do that?

teal viper
rich adder
fickle stump
hearty glade
#

and here's how it normally looks (both editor and other phone)

#

I really don't have other phones to try, but it's probably a device issue, right?

#

or am I doing something wrong on my Update()?

rich adder
cedar prairie
#

it has something to do with my lights im so frustrated. Looks like it is fixed but then on runtime its broken

subtle sedge
#

is there a way to only make a input detection work once?

polar acorn
#

Set a boolean after you detect it the first time, and only do the thing if it's un-set

wintry quarry
vagrant mist
#

I'm having an issue where if I have more than one enemy in a scene, I can only destroy one of them, like the other is unaffected

Enemy Health Script

public class EnemyHealth : MonoBehaviour
{
    public int health;
    public int maxHealth = 3;
    public SpriteRenderer enemySprite;
    public EnemyChase enemyChase;

    private void Awake()
    {
    }
    void Start()
    {
        health = maxHealth;
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void FixedUpdate()
    {
        Debug.Log("Enemy Health: " + health);
    }
    public void TakeDamage(int damage)
    {
        health -= damage;
        if (health <= 0)
        {
            enemySprite.enabled = false;
            enemyChase.enabled = false;
            Destroy(gameObject);
        }
    }
}

Weapon Damage Script

public class WeaponDamage : MonoBehaviour
{
    EnemyHealth enemyHealth;
    public int damage;
    void Start()
    {
        enemyHealth = GameObject.FindGameObjectWithTag("Enemy").GetComponent<EnemyHealth>();      
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Enemy"))
        {
            if (enemyHealth != null)
            {
                enemyHealth.TakeDamage(damage);
            }
        }
    }
}
rough granite
#

instead of doing this in start
enemyHealth = GameObject.FindGameObjectWithTag("Enemy").GetComponent<EnemyHealth>();

fair scarab
#

as a beginer i was wondering whether id have an easier time with unity or unreal engine

rough granite
#

do something like
enemyHealth = collision.GetComponent<EnemyHealth>();
in the collision

#

cause currently you get the first known instance of the enemy not all or the one that is meant to take damage so if you hit one enemy the other could take damage

vagrant mist
#

alright, lemme see

rough granite
fair scarab
#

oh sorry

vagrant mist
rough granite
# vagrant mist thank you, that seemed to do it

just to check it should look like this


    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Enemy"))
        {
            EnemyHealth enemyHealth = collision.GameObject.GetComponent<EnemyHealth>();
            if (enemyHealth != null)
            {
                enemyHealth.TakeDamage(damage);
            }
        }
    }
vagrant mist
#

yup, I got it to work with that

fickle stump
worthy coral
#

Movement systems are pretty hard to make. Mine features procedural animations for foot placement, leaning, and changing spine rotation based on the speed of movement and slope you're running on, it has acceleration and deceleration with editable AnimationCurves to change the speed over time for acceleration and deceleration, it also has thresholds for the difference between feet positions, speed, and a bunch of other factors before IK applies, and it has animations for hard stops, soft stops, and manually animated transitions between states. It also has things like variable rotation speed depending on how fast you turn the joystick and how big the delta of the transform's forward vector and the input vector is. How good is my movement system compared to a AAA game for example? And is there anything else i could do to make it better?

fickle stump
#

I'm struggling a bit with coroutines. My plan is to have an button that starts an event after like 3 Seconds. What am I dong wrong:

(``` public class DisableAndEnableButton : MonoBehaviour
{
[SerializeField] GameObject[] objectToDisable;
[SerializeField] GameObject[] objectToEnable;

[SerializeField] bool isCoroutine;

private IEnumerator coroutine;

public void Start()
{
if (isCoroutine == true)
{
StartCoroutine(coroutine);
}
}

public void SimpleDisable()
{/*
if (objectToDisable.activeInHierarchy == true)
{
objectToDisable.SetActive(false);
}
else
{
objectToDisable.SetActive(true);
}*/

  foreach (GameObject obj in objectToDisable)
  {
     if (obj.activeInHierarchy == true)
     {
        obj.SetActive(false);
     }

     else
     {
        obj.SetActive(true);
     }
  }

}

public void DisableAndEnable()
{
foreach (GameObject obj in objectToDisable)
{
obj.SetActive(false);
}

     foreach (GameObject obj in objectToEnable)
     {
        obj.SetActive(true);
     }

}

private IEnumerator WaitAndDisable()
{
yield return new WaitForSeconds(2);

  foreach (GameObject obj in objectToDisable)
  {
     obj.SetActive(false);
  }
     
  foreach (GameObject obj in objectToEnable)
  {
     obj.SetActive(true);
  }

}
} ```)

#

oh god

#

okay i'm only making it worse sorry ._.

mystic flume
#

i just finished learning vector3 and raycasting what should i do now?

naive pawn
#

whatever you want to

north kiln
naive pawn
#

sharing the issue you have would be really helpful to pinpoint the cause btw

fickle stump
#

Sorry it's getting late, my brain isn't braining anymore.
I think I'm just too tired cuz I can't even realise what I'm doing wrong

lofty mirage
#

is
private IEnumerator coroutine
and
private Coroutine coroutine
the same?

wintry quarry
#

There are a couple circumstances where they can be used interchangeably in the Unity API but they're not the same

#

Namely for StopCoroutine and when yield returning them

lofty mirage
#

So which one should be preferred?

#

I'm used to writing private Coroutine coroutine

#

but here I saw private IEnumerator Coroutine so I'm confused now

naive pawn
#

if you're only using them for those apis where you can use either, imo it doesn't really matter, just be consistent

#

i tend to use Coroutine since it's unambiguous as to what it's for

lofty mirage
#

What does IEnumerator even mean

#

Like Coroutine reads nicely

#

you make a new temporary thread from my understanding

naive pawn
#

(not a thread, really. just something to check back on every frame)

#

IEnumerator is just something that can provide multiple other values

#

in the case of a coroutine, it's being used to provide YieldInstructions

lofty mirage
#

Okay

#

So it's more readable if I use
coroutine = StartCoroutine(myRoutineFunc())
rather than
myIEnum = myRoutineFunc()
?

naive pawn
#

well those 2 don't do the same thing

#

consider these:

coroutine = StartCoroutine(Routine());
// VS
StartCoroutine(coroutine = Routine());
// or
coroutine = Routine();
StartCoroutine(coroutine);
latent mortar
#

just finished junior programmer what should i do now

charred spoke
#

Make game

latent mortar
charred spoke
#

Make game, get better at coding

latent mortar