#💻┃code-beginner

1 messages · Page 338 of 1

zinc shuttle
#

i tried else if but its stuck at 1 kill for every kill

modest dust
#
if(isEnemy)
{
  if(killcount==1)
  ...
}```
And yeah, an array.
modest dust
zinc shuttle
modest dust
#
public AudioSource SRC;
public AudioClip[] KillClips;

...
if (isEnemy)
{
  Destroy(enemy);
  Debug.Log("I'm awesome");
  SRC.clip = KillClips[killcount];
  SRC.Play();
  ++killcount;
}```
modest dust
#

You're gonna have a bad time doing anything in Unity without that

#

Unless it's the kind of scenario where you're on a deadline

zinc shuttle
modest dust
#

Otherwise, for yourself, there's no reason not to

zinc shuttle
modest dust
#

There is a lot of repetition and you're assigning a new clip for each killcount number

#

What's a "numbered set of elements"? An array.

zinc shuttle
modest dust
#

Either way, I gave you an example above

languid spire
zinc shuttle
modest dust
#

Show what you tried

#

And make sure you assigned the correct audio clips in the inspector in the array

zinc shuttle
zinc shuttle
#

also checked the debug it only print 0killed ofr every kill

modest dust
#

Is it the same instance of BulletEffect each time or different ones?

teal viper
modest dust
#

Ah, missed the destroy

#

If you want a shared kill count then make it static

modest dust
#

Or move it elsewhere

zinc shuttle
teal viper
zinc shuttle
#

or i should make it static

modest dust
#

Just make it static for now

zinc shuttle
zinc shuttle
teal viper
#

Static is a pretty bad solution though. You're supposed to keep kill count in some sort of a manager class or something.

zinc shuttle
#

it worked!

modest dust
#

That's why I said he could move it elsewhere, but for now, if he only uses it for the audio clip, it's fine

zinc shuttle
teal viper
#

Having the bullet manage audio sources and audio clips and have them on the prefab is also pretty silly.

bold nova
#

Does anyone know how to make a generic monobehaviour script? I wanted to make one, but I cant attach it to an pbject because "Names do not match"... Here is what I've got

public class ObjectPooler <T>: MonoBehaviour
where T : MonoBehaviour

willow scroll
#

You may create a script with a generic MonoBehaviour class, but if you want to assign it to the GameObject, you'll have to have a non-generic class derived from it

hallow totem
north kiln
eternal falconBOT
fierce shuttle
#

Why not?

topaz mortar
#

Why does this function allow me to return null? In other places (can't remember exactly where, but I think most of the time) it won't allow me to return null when it's expecting an object to be returned.

{
    return null;
}```
north kiln
#

If Character is a reference type then it can be null

topaz mortar
#

is that a unity thing? I think it's on my C# module server that it won't allow stuff like that

north kiln
#

It's a fundamental C# thing

topaz mortar
#

well it is just a warning

#

but I don't get this in Unity

hallow totem
north kiln
hallow totem
#

VSCodium isn't supported.

north kiln
#

Isn't that just a weird VS Code?

short hazel
# topaz mortar but I don't get this in Unity

It's the Nullable Reference Types analyzer shipped with newer .NET versions.
Since your method doesn't return a Task<Character?> (indicates it might be a Character or null) you get the warning

#

This doesn't affect performance of the compiled code, they're a bunch of analysers that can be disabled.

hallow totem
#

Yeah so supporting it should be pretty easy but I guess Unity doesn't want to do it because it's unofficial.

north kiln
#

Can you not follow the Vs Code configuration for it? Or do you get stuck somewhere in those instructions

topaz mortar
#

been using Task<Character?> on my server, but I guess I don't need to then

north kiln
#

It's an annotation hint that helps writing safer null-handling code

#

If you can use it, it's a helpful tool to have

topaz mortar
#

if I have:
Character character = await GetPlayerStats();
and it returns null, will that throw an error or will it just assign null to character?

north kiln
#

Sadly Unity Objects are weird and so it's less useful for Unity projects, though you can work with it there

#

It will just assign null

topaz mortar
#

so what's the warning for then? 😛

hallow totem
north kiln
#

By annotating your code you let the IDE help you be sure you won't get unexpected null reference exceptions

#

By default Unity projects have none of that, so you get no help writing safer code

woven crater
#

whats the difference?

gaunt ice
#

the one under uielement is ui toolkit, which the top one is ugui ie the ui gameobjects you added to canvas gameobject

woven crater
#

thank

buoyant perch
#

anyone know how i can make it to listen

rocky canyon
#

u click the drop down on Path

hard ledge
#

I'm struggling to design how I want to handle data exactly in my project. I'm trying to design a simple RPG skillset, and this is what I've come up with so far:

  • A MasterAttribute script, which I then generate scriptable objects off, for the actual skills, they look like the attached pic.
  • A manager script to create a defined sized array, then populate it

What I'm confused about is; In my own design I don't know how you would interact with the gameobjects (the attributes), but also with a player + enemies, how would I manage their attributes as well, seperately?

I am trying to plan a modular system that could be used for various data like currencies, stats, etc that can be extended in the specific items if needed.

#

Just looking for advice, this seems like a bad approach, but everything else I've seen is too simple, or hard coded...

kindred halo
#

I have this code where the playerSpeed gets decremented when this function is called.
but when running
Instead of decrementing with the given value every sec
It decrements slowly like a loading bar
i don't even know how to explain

void DecreaseSpeed(float speedDecrease)
{
    playerSpeed -= speedDecrease * Time.deltaTime;
}```
teal viper
teal viper
kindred halo
teal viper
#

And in that now, gameObjects for skills is a bad idea imho.

queen adder
#

Does anyone know if I'm able to use Sprite Editor without importing a PSB file, I created my character out of shapes inside of my scene, and... I used a lot of shapes

#

I want to animate it using IK, but every tutorial I see, keeps importing a PSB file, but what to do if my character was built in the scene, and not in Photoshop

teal viper
#

So I don't see an issue..? Is the issue that it jumps to 80?

spiral narwhal
#

What should I do instead?

kindred halo
#

not decrease over time like that

teal viper
teal viper
queen adder
# teal viper Can you share an example of a tutorial that does this?

Use inverse kinematics to move your character limbs with ease!

Rig up your 2D character in Unity using Unity's 2D animation library (creating a skeleton). Next, I'll show you how to hook up IK (inverse kinematics) to your character to perform realistic joint movements. Finally, I'll show you how to use all of this together to create great-looki...

▶ Play video
teal viper
teal viper
#

Why would you need something "instead"?

kindred halo
teal viper
queen adder
# teal viper Can you share an example of a tutorial that does this?

Wanna learn how to make your characters come alive? Then Skeletal Animation is for you!

This video is sponsored by Unity.

You need to use Unity 2018.3 or later to use these tools.

Unity is hosting a 2D Challenge - Check it out: https://ole.unity.com/2dchallenge

● Rigging documentation: https://bit.ly/2S1Xn04
● IK documentation: https://bit.l...

▶ Play video
topaz mortar
#

How would I lock a function from being called multiple times at nearly the same exact time?
I had a bool in it that returns if it's true, but that's too slow it seems?
I looked up how lock in C# works, but that's not allowed in an async function

{
    // Don't allow this to be called again until we get a response
    if (waitingForCombatLogs)
    {
        return;
    }

    waitingForCombatLogs = true;```
teal viper
kindred halo
teal viper
topaz mortar
#

the function can get called from multiple places (at the same time)

#

not multithreading as far as I know

#

but it still got called 2x at the same time somehow

#

wait maybe something else went wrong 🤔

teal viper
teal viper
topaz mortar
#

yeah it's just getting called again really fast, but it completes the first time

#

so I have some other error somewhere

hard ledge
teal viper
topaz mortar
teal viper
queen adder
teal viper
queen adder
#

I really doubt it, I've spent a whole week on it, so it's more than just a hand full of sprites, it's.... colossal

topaz mortar
queen adder
#

it started off with me just messing around, and I fell in love with it

teal viper
queen adder
#

I may have goofed... I'll figure it out nw, thanks for your help @teal viper

languid spire
topaz mortar
languid spire
#

It's still async, just sharing a thread

teal viper
loud mango
#

!code

eternal falconBOT
loud mango
#

any ideas on how to solve it?

languid spire
loud mango
#

then the function doesnt take the health

#

cuz function is static

languid spire
#

you have used a static variable because you thought it made your life easier instead of thinking about what you need to do

loud mango
#

that what should i do sensei 😭

languid spire
loud mango
#

it wont accept the health

languid spire
#

do the job properly instead of trying to implement shortcuts which will come back and bite you in the arse

loud mango
#

so i decrease the health manually from the gun script?

languid spire
#

because the method is static

#

so take the static off the method as well

loud mango
#

then how do i call it from the gun?

#

when the raycast hits the enemy

languid spire
#

you use GetComponent to get the correct TakeDamage instance for THAT enemy, then call the method on that

loud mango
#

can u give an example in 1-2 line of code? i dont understnad ;-;

languid spire
#

you mean can I write to code for you?, No

loud mango
#

no no, just an example that does not relate to my code

#

i fucked around to find out but couldnt find out 😦

languid spire
#

ok

OnCollisionEnter(Collision other) {
TakeDamage td = other.gameObject.GetComponent<TakeDamage>();
td.TakeEnemyDmg(5f);
}
loud mango
#

but my bullet is raycast

#

oh wait got it

#

sorry

charred spoke
#

if(hit) GetComponent

limber anchor
#

Hey still working on my movement script rn I am having the issue that my player is falling way to slow but If I add more mass to my player it will simply jump less high instead of actually falling quicker
code: https://paste.ofcode.org/39xPsVPu2uWPmCXyMTTRFJV

limber anchor
loud mango
#

idk if that is preffered or not but i did that for my game

limber anchor
loud mango
#

lol me too before i created my current game

limber anchor
languid spire
#

But increasing physics gravity will also affect the jump height, gravity works both ways just like irl

kindred halo
#
 playerSpeed -= 12f * Time.deltaTime;

It's not multiplying by 12
but keeps decrementing by one
help

loud mango
#

and the gravity

limber anchor
languid spire
dreamy junco
#

is it normal for a button to get pressed when i'm pressing space bar in flappy bird, when i press the button the music changes once when i then hit space bar the button gets pressed for a period of time, i can even see the color changing

limber anchor
loud mango
#

oh nice

dreamy junco
#
    {
        if (current == 1)
        {
            source.Stop();
            sourceTwo.Play();
        }

        else if (current == 2)
        {
            sourceTwo.Stop();
            sourceThree.Play();
        }

        else if (current == 3)
        {
            sourceThree.Stop();
            source.Play();
        }

        if (current == 1)
        {
            current = 2;
        }

        else if (current == 2)
        {
            current = 3;
        }

        else if (current == 3)
        {
            current = 1;
        }
    }```
dreamy junco
#

this is the code to change the music

kindred halo
# languid spire you'll need to show more !code than that

The function(I replaced it with 12 to see if it works)

 void DecreaseSpeed(float speedDecrease)
 {
     playerSpeed -= speedDecrease * Time.deltaTime;
 }

here's how it's called

 else if (isSliding)
 {
     SlideMovement();
     slideTimer +=Time.deltaTime;
     if (slideTimer <= maxSlideTimer) { DecreaseSpeed(slideSpeedDecrease); }
     if (slideTimer >= maxSlideTimer)
     {
         isSliding = false;
     }
 }
languid spire
eternal falconBOT
#

:teacher: Unity Learn ↗

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

dreamy junco
#
     {
         myRigidbody.velocity = Vector2.up * flapStrenght;
         this.gameObject.GetComponent<SpriteRenderer>().sprite = FlappingBird;
         source.PlayOneShot(clip);
         timer = 0;
     }```this is the code to flap the bird
limber anchor
rocky canyon
#

changing the gravity is a solution.. but this kinda throws off the entire project.. all ur forces will need adjusted..
i prefer to add a downwards force when the player isn't grounded... u can just tack on a bit of extra gravity

  gravitySim += playerSettings.gravity * Time.deltaTime;``` ofc mines a character controller.. but the same could work for a rigidbody.. by adding it to the velocity
limber anchor
rocky canyon
limber anchor
languid spire
loud mango
#

thanks Sensei its works now

rocky canyon
#

basically just set the .y to zero

limber anchor
languid spire
rocky canyon
kindred halo
languid spire
#

@dreamy junco

 whatever[] source;
 public void changeMusic()
    {
            source[current].Stop();
            current++;
            if (current >= source.Length) current = 0;
            source[current].Play();
    }
dreamy junco
#

thx

languid spire
# dreamy junco thx

don't just copy/paste, take some time to think about the code and understand it

dreamy junco
#

yeah i'm bad at progaming and thats better but the problem with the button beeing pressed when i press the spacebar isn't gone

languid spire
dreamy junco
#

i don't know when i press the button once it changes the music once but every time after that it gets pressed when i press the space bar

#

like 2 seconds long after i pressed it

languid spire
#

that makes no sense, a button is pressed on an OnClick event, that has nothing to do with the spacebar

dreamy junco
#

even the color of the button changes is that a bug

#

it's like i would press the button but with the space bar

languid spire
#

I cannot imagine it is a bug, it sounds more like a problem with your keyboard

dreamy junco
#

the problem with the score and the bool isn't solved yet, too

languid spire
#

tbh, it feels like you are blundering around in the dark. You should take some time to !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

dreamy junco
#

thank you for the help

brave compass
#

The reason it starts happening only after you click on a button is because you're moving the focus to that button by doing that, and then it starts listening to keyboard events.

languid spire
dreamy junco
#

oh ok thank you

scarlet skiff
#

i have this code that looks for players in the scene, so that monsters can then choose a random player and follow them, problem is if someone late joins, or not just late join, whoever isnt first would miss out on being tracked and added to this hashset because it runs in awake method, i could simply run it in update as well but i feel like there gotta be a more effecient method, like only when a new player is summoned/joins or leaves would it update this, how can i approach such a solution?

Script (just in case it is needed): https://gdl.space/orafuyibeb.cs

wintry quarry
#

(make it a Singleton)

tough cave
#

How can I make a referencable object to a script with the use of the editor? Like this 'pop up' is a template for different types of problems, that implements the interface IProblem. like StudentsConfusedProblem... I want toi have the popup to be easily interchangable between probleems. Hoped public IProblem problem worked, but its not showing up in the editor. Or do I have to hardcode it.

swift crag
#

It's not a UnityEngine.Object type (duh, it's an interface!) and it's not one of the other types Unity allows you to serialize (e.g. int, or a [System.Serializable] class)

#

There are a few ways to deal with this

#

One would be to make an abstract class. This is appropriate if everything that implements IProblem is going to be a behaviour or a scriptable object

scarlet skiff
swift crag
#

it's reasonable if you also want to un-register in OnDisable

stuck palm
#

why is it that when i want to print an int by itself i have to go int.tostring but if i want to do a string and and int i dont have to write dostring?

swift crag
#

beacuse you're probably using the + operator

scarlet skiff
stuck palm
swift crag
#

There are three + operators that involve strings

#
string operator +(string x, string y);
string operator +(string x, object y);
string operator +(object x, string y);
#

so you can add a string to literally anything

#

it just calls ToString() on the object

stuck palm
#

oh i see

#

can i make my own operator like that?

swift crag
#

This also works fine, though:

Debug.Log(123);

Debug.Log can take an object, which it then calls ToString() on

#

If you have a method that only takes a string, then it will not accept an integer: there is no implicit (i.e. automatic) conversion from int to string

swift crag
willow scroll
stuck palm
willow scroll
#

E.g. in your own class

stuck palm
#

i was just wondering 😅

#

hypothetically

#

just for future knowledge

swift crag
#

but yes, you can both:

  • define your own + operator
  • define an implicit conversion to string (which can just call ToString() if you want)
willow scroll
stuck palm
#

thats interesting

#

thank you

#

idk why i would do it though

swift crag
#
public struct SmoothFloat
{
    public float value;
    public float target;
    private float velocity;
    public float time;

    public float Update()
    {
        value = UnityEngine.Mathf.SmoothDamp(value, target, ref velocity, time);
        return value;
    }

    public void Set(float target)
    {
        this.target = target;
    }

    public static implicit operator float(SmoothFloat self)
    {
        return self.value;
    }
}
#

an example of the latter

willow scroll
# stuck palm idk why i would do it though
public static MyClass operator +(MyClass a, MyClass b) =>
    a.variable + b.variable;

public static MyClass operator -(MyClass a, MyClass b) =>
    a.variable - b.variable;

public static MyClass operator *(MyClass a, MyClass b) =>
    a.variable * b.variable;

public static MyClass operator /(MyClass a, MyClass b) =>
    a.variable / b.variable;
stuck palm
#

cool

#

i learnt something new lol

#

thanks guys

willow scroll
#

You may usually need to override the ToString method

#

E.g. you have a class Vector2Float, and you want it to be printed as (x, y)

public override string ToString() => $"({x}, {y})";
bitter walrus
placid condor
#

dont know if this fits in this channel but why wont the hub let me create a new project?

bitter walrus
#

exactly under your curser

placid condor
#

ooh

#

ok ty

#

didnt know i had to do that

#

thought i can just leave it if im working alone

bitter walrus
candid burrow
#

Hey guys, quick question. I'm using the navmesh system to move my player, and i did the boot logic for my game in a way where i create my player in a different scene from where my gameplay actually happens.

So.. there is no navmesh whenever i create my PlayerCharacter, how can i go around that problem?

placid condor
swift crag
swift crag
#

I don't know what this class is.

#

I'm guessing it's something that is editor-only, and thus does not exist when you build the game

#

i can find only one hit, which is a deleted GitHub Gist

#

which does look like an editor script

keen dew
#

You can see its code at the start of the video (it's an editor script)

swift crag
#

ah, nice

#

so yes, that means you cannot use this class from any non-editor code

teal charm
#

!bug

eternal falconBOT
#

🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.

📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!

💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.

For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting

swift crag
#

if you're using it to set things up at runtime, you'll need to either make this class available at runtime (very easy if it ShadowCaster2DCreator doesn't rely on editor classes!) or do the setup ahead of time

rich wasp
#

hi guys I'm very noob and following a tutorial on hex cell generation, making the splat map for the textures currently. is there a way to do something other than a simple fade between two values? like instead of a simple gradient have the two color params be lerped with a noise mask as the factor?

            TriangulateEdgeStrip(e1, color1, e2, color2, hasRoad);
swift crag
#

so that you get a noisy transition?

#

consider applying a lerp or smoothstep function whose start and end values are adjusted by noise

abstract finch
#

Whenever you send a struct to a new function, is a new one created or is it the same one? Wierd question but I'm planning on using something called ActionInfo containing alot of data (mostly static) so Im debating on whether to use a struct or a class for this.

swift crag
#

you pass it by value, so a copy of the struct goes on the stack

#

(rather than a copy of the reference, for reference types!)

wintry quarry
swift crag
#

If it's a ton of data -- yep (:

#

in is a reasonable choice if you have a big struct you'd like to pass to something

abstract finch
#

ill look it up

wintry quarry
#

whereas out requires you to modify it

abstract finch
swift crag
#

(so that it is provably assigned to!)

rich wasp
swift crag
#

actually, i might instead just use the noise to modify the value

float noisePower = 0.5f - Mathf.Abs(0.5f - value); // we don't want to go out of the 0..1 range
float noisyValue = value + Random.Range(-noisePower, noisePower);
#

That ensures that 0 and 1 aren't touched

#

0.5 can get remapped to 0..1
0.25 can get remapped to 0..0.5

swift crag
abstract finch
#

public void StartAction(in ActionInfo actionInfo)
If i passed it to this iterator below would it still be the same struct? It said iterators cant have in out or ref so I have to make a function
private IEnumerator HandleAction(ActionInfo actionInfo)

wintry quarry
#

and since you can't... no

abstract finch
#

Hmm I see

#

I guess i can store it inside the class and run it

unique gust
#

can someone help me again? i made another try using another logic to make the snake game and make an ienumerator to make the snake movement and make an startroutine but the unity editor is saying the that the variable is declared but not used

timid hinge
#

hi did someon knows where can i find good 2d assets for unity

wintry quarry
#

also that sounds like a warning, not an error

frosty hound
real grail
# unique gust can someone help me again? i made another try using another logic to make the sn...

Also this logic is flawed you are always setting position to 0. If you go down line by line you will see what i mean.

   IEnumerator MoveSnake()
        {
            yield return new WaitForSeconds(DelayStep);
            Vector3 nexPos = Vector3.zero;
            switch (MoveDirection)
            {
                case Direction.UP:
                    nexPos = Vector3.up;
                    break;

                 case Direction.DOWN:
                    nexPos = Vector3.down;
                    break;

                case Direction.LEFT:
                    nexPos = Vector3.left;
                    break;

                case Direction RIGHT:
                    nexPos = Vector3.right;
                    break;
            }
            nexPos *= step;
            Head.position += nexPos;
            StartCoroutine("MoveSnake");
        }
#

Also dont have Ienumerators in update.

unique gust
wintry quarry
#

that's a local function

#

and yeah

#

you put your coroutine INSIDE Update

#

why would you do that?

#

That also means it's not going to work with StartCoroutine.

unique gust
#

i also put the coroutine in star update

wintry quarry
#

no you didn't

#

you put a StartCoroutine call in Start
the coroutine itself you put inside Update

tough cave
#

What is me missing ? :{ Is this not how u do it? I have a popup that needs to spawn on the position of the gameObject. :c
but still spawns in the middle of the screen.

public class StudentManager : MonoBehaviour
{
    public Popup popup;
    // Start is called before the first frame update
    void Start()
    {
        
        Invoke("startProblem", 3);
    }

    public void startProblem()
    {
        popup.ShowPopup();
        positionPopup();
    }

    public void positionPopup()
    {
        popup.transform.position = gameObject.transform.position + new Vector3(0, 1, 0);
    }
wintry quarry
#

they do not live in the same coordinate space

wintry quarry
#

it should be:

class A 
{
  void Method1() 
  {
  }

  void Method2() 
  {
  }
}``` BUt you have this:
```cs
class A 
{
  void Method1() 
  {
     void Method2() 
     {
     }
  }
}```
#

don't do that

#

don't out methods inside other methods.

unique gust
#

oh i think i get...i have to put the ienumerator outside the update method right?

wintry quarry
languid spire
buoyant finch
#

how do I make a character follow the player like in pokemon heartgold and to change its mesh while following pls help

languid spire
languid spire
#

ok, smartarse, how would you do it physically

unique gust
#

I just wanted to try creating my first game but I'm getting frustrated with it

wintry quarry
#

Sure, frustration is common when you first learn programming

rich adder
#

if you start too complex too early, it will happen

languid spire
rich adder
#

haha yeah if search the words just want/ed to in this discord, quite interesting results

languid spire
# unique gust i don't get it

exactly, and that is why you are frustrated. Using the word 'just' implies that is is easy and simple, believe me there is nothing easy or simple about game development

teal charm
#

@unique gust btw async methods make ur code look cleaner than ienumerators

teal charm
# languid spire bet?

in this context i think itll look more modular and cleaner than startcoroutine(...aidadadjashd,..)

#

my opinion

rich adder
#

Unity doesnt handle async as graceful as Coroutines

#

it does in Unity 2023+ with Awaitable class

teal charm
rich adder
#

it was a slow and painful process 😛

#

but we here

unique gust
languid spire
teal charm
unique gust
wintry quarry
#

YouTube tutorials in general aren't very good

teal charm
wintry quarry
#

it's the sad state of things - and honestly the most entertaining ones usually get to the top of the YouTube charts, not the good ones

teal charm
#

i started using events instead of simple method classes and in the end i got lost

#

then i learned the true value of events

languid spire
# teal charm can i have a snippet

sure, here is one method split into 2 to allow both sync and async

        public void Scene(Scene scene)
        {
            Task t = new Task(async () => {
                IsDone = false;
                await SceneAsync(scene);
                IsDone = true;
            });
            if (isAsync)
                t.Start(TaskScheduler.FromCurrentSynchronizationContext());
            else
                t.RunSynchronously(TaskScheduler.FromCurrentSynchronizationContext());
        }

        async Task SceneAsync(Scene scene)
        {
            if (scene == null || !scene.IsValid())
            {
                Serialize.Serializer.Log("Missing or invalid scene");
                return;
            }
            components.Clear();
            for (int i = 0; i < fileHeader.objHeaders.Count; i++)
            {
                Serialize.ObjHeader oh = fileHeader.objHeaders[i];
                if (oh.objType == Serialize.ObjHeader.ObjType.GameObject)
                {
                    await makeGameObject(oh);
                }
            }

            for (int i = 0; i < fileHeader.objHeaders.Count; i++)
            {
                Serialize.ObjHeader oh = fileHeader.objHeaders[i];
                if (oh.objType == Serialize.ObjHeader.ObjType.GameObject)
                {
                    GameObject gameObject = await completeGameObject(oh);
                    if (gameObject.transform.parent == null)
                    {
                        SceneManager.MoveGameObjectToScene(gameObject, scene);
                    }
                }
            }

            endLoad();
            Serialize.Object.Clear();
        }
buoyant finch
languid spire
languid spire
# buoyant finch yes

Ok, so thats what you do in your code, you keep the following object a set distance behind your player. See that wasn't so hard was it?

buoyant finch
languid spire
teal charm
languid spire
teal charm
languid spire
#

for save and load, yes

elder osprey
#

I am making an upgrade system for my game. My current idea is to create a scriptable object that holds a struct array with the data of each upgrade. For example: ```cs
[System.Serializable]
struct UpgradeData {
public int upgradeID = 0;
public string upgradeName = "name"
}
public UpgradeData[] upgradeData;

elder osprey
#

Would this be an efficient way to create this, or am I using arrays wrong?

languid spire
#

also an index to know which upgrade is current

rich adder
#

array is fine if you don't need to add/remove additional upgradeData at runtime

elder osprey
languid spire
true pasture
languid spire
true pasture
#

its just a textbox though

#

its not an input field anymore

languid spire
#

if it's just a text field why are you trying to parse it, you are the only one that can change it's contents

rich adder
#

have you tried actually printing textbox.text before parse

true pasture
#

thats not the error though, the error is this line

#

im just trying to turn my int into a string

languid spire
polar acorn
#

Whatever it is, it's not an int

rich adder
languid spire
true pasture
#

sorry im turning a string into an int

polar acorn
rich adder
#

we can see that

true pasture
#

and i checked both thier types and they are strings

polar acorn
#

But whatever you're passing to it isn't an int

#

It can't parse whatever you're giving it

rich adder
polar acorn
#

So that's why the suggestion was to log it and see what it is

rich adder
#

not that its a string

polar acorn
#

So that we can see why it's not able to parse into an int

languid spire
#

because he is using TextMeshProUGUI which has a null terminator

rich adder
#

yeah but do *they * know that

languid spire
#

I think I said it, twice

swift crag
#

a null terminator? that'd be surprising

true pasture
#

I already changed it to that TMP_Text and it didnt fix it

rich adder
swift crag
#

changing the type of the variable doesn't change the component you are using

languid spire
swift crag
true pasture
#

i already tried Trim()

polar acorn
ivory bobcat
swift crag
#

a non-breaking space, perhaps

polar acorn
rich adder
languid spire
#

TextMeshProUGUI.text != TMP_Text.text

true pasture
green ether
rich adder
polar acorn
#

You can use that type to hold both kinds of TextMeshPros

green ether
#

ah ok

#

never had a need for that yet

true pasture
#

so i have strings in the Parse is that not what parse takes? I swear I looked at the docs

languid spire
swift crag
swift crag
#

and, actually, looking at how text is implemented...

#
    private string InternalTextBackingArrayToString()
    {
        char[] array = new char[m_TextBackingArray.Count];
        for (int i = 0; i < m_TextBackingArray.Capacity; i++)
        {
            char c = (char)m_TextBackingArray[i];
            if (c == '\0')
            {
                break;
            }

            array[i] = c;
        }

        m_IsTextBackingStringDirty = false;
        return new string(array);
    }
#

It explicitly does not include a null terminator

languid spire
true pasture
ivory bobcat
#

It may not be a number

swift crag
#

ah, but array will contain null characters in any indices that weren't assigned to

#

so even though we never assign a null terminator, they'll at least exist

true pasture
#

the only thing coudl be whitespace, but I tried Trim() already,l Fen mentioned nonbreaking whitespace?

swift crag
#

Iterate over the string and log the actual codepoint of each character

#

this will reveal anything particularly funny

polar acorn
polar acorn
#

because "Cheese and Bacon Omelette" is not an integer

true pasture
#

yeah I know, I understand I just looked each char in the array and there is a soace at the start

swift crag
#

it would be useful to see the string first, yes

languid spire
true pasture
#

trim says it removes leading whitespace

gaunt ice
#

see if there are zero width spaces

polar acorn
true pasture
#

no

ivory bobcat
#

Maybe show your implementation (how you're using trim)

true pasture
languid spire
ivory bobcat
#

Maybe it isn't a number at all, whatsoever.

true pasture
#

this has to happen, Its not something to try

polar acorn
# true pasture

Important note:
"" is also not an integer. If the string is empty, that's also a parse failure

swift crag
#

you have still failed to actually show us the string you're trying to parse

languid spire
ivory bobcat
#

It's a secret 🙂

true pasture
#

no its just that I explained it, but here a screenshot. I said it has a leading whitespace heres the string when I enter 14

rich adder
#

so its blank?

swift crag
#

this is individual characters

true pasture
#

no its (whitespace) 1 4

ivory bobcat
#

Or some non printable character

rich adder
#

probably should label your Prints.

#

print("firstnumber:" + firstnumber)

true pasture
#

its just that trim isnt removing that first character

#

thats the problem, I know why parse doesnt work now

ivory bobcat
#

Maybe it isn't a whitespace character?

polar acorn
ivory bobcat
#

Cast the character to int in the print

gaunt ice
wintry quarry
true pasture
#

its 8203, how do I find the character that represents that? is it unicode?

wintry quarry
swift crag
#

ha, I knew it (:

true pasture
#

congrats

#

lol

swift crag
#

where is this string coming from?

true pasture
polar acorn
swift crag
#

okay, so you typed a string into the inspector?

#

did you copy and paste the string?

polar acorn
#

Because if you just typed it in then why not just use that value instead of getting it from the text element

true pasture
#

no its being input from my buttons that I clicked

#

the buttons have a monbehaviour with the value they add to that textbox

swift crag
#

sounds like the text starts out with a single zero width space in it, instead of being actually empty

true pasture
#

so I can just clear that textbox on awake?

rich adder
true pasture
#

lemme try that

ivory bobcat
#

Why does it have that zero width space to begin when?

swift crag
#

just...don't have a zero width space in the text component to begin with (:

true pasture
#

thats the dream

swift crag
#

click the text field in the inspector

#

hit backspace

#

gone

#

the cursor winds up moving forwards slightly when i erase a zero-width space, amusingly

wintry quarry
swift crag
#

it's not a TMP_InputField

#

it sounds like they're just appending characters as they click on buttons

true pasture
#

i will find out which

#

setting it to empty on awake is what worked

#

no idea why its starting with a zerowdith thing

swift crag
#

if not, i'm not clear where "validations" would be

tranquil hollow
#

why when i die my dead animation still in a loop?

polar acorn
swift crag
#

"Loop Time" is a property of the animation clip

tranquil hollow
polar acorn
west sonnet
#

I want to move this object to the left. What's the easiest way to do that?

polar acorn
wintry quarry
#

If you just use a single bool it would be better:
RunningRight = true means you're going right
RunningRight = false means you're going left

west sonnet
#

Okay, makes sense. Thanks

polar acorn
swift crag
#

or, if you want something more generalized...

#
Vector3 moveDir = Vector3.right;

public void Flip() {
  moveDir *= -1;
}
timber tide
#
Quaternion.LookRotation(Vector3.zero)

Logically, would your eyes implode?

wintry quarry
#

I think that's how you achieve nirvana

wintry quarry
polar acorn
#

Usually by transitioning out of it whenever a condition is met

tranquil hollow
tranquil hollow
polar acorn
#

but out of it instead

buoyant finch
#

I managed to do this but how do I make it follow at a set distance and stay behind and not get away from the player

rich adder
true pasture
#

Okay thanks yall for the help, I did get it working still don't know why theres a zerowidth whitespace thing, but I don't have time to care.

brazen canyon
#

Hey guys, I have this global Array in class A, there are a few methods refered to it, and there are a few methods calls those methods.
Now ...
In another class called class B I wanna call a method which process this Array from class A, but this Array is currently only contain 0s, now I want to change a few elements of this Array.
Can I override or something like that to this Array ?

buoyant finch
brazen canyon
west sonnet
#

I'm getting this error, but my script doesn't reference an object?

tranquil hollow
rich adder
wintry quarry
buoyant finch
wintry quarry
polar acorn
rich adder
#

detection is struct 😦

wintry quarry
#

indeed but we can also secretly do this because of operator magic:

if (detection) {
  // you hit something
}
else {
  // you didn't hit anything
}```
ivory bobcat
polar acorn
#

Leaving only one culprit!

rich adder
polar acorn
buoyant finch
rich adder
median stream
#

hey guys i am trying to make a 2d game but when i implemented the wall jump the player continuously started flipping can you help me solve it. it would be a great help to me if you guys can help me out as i dont know about cooding much. here are the scripts i used

rich adder
#

If you use Navmesh agent increase acceleration/speed

median stream
buoyant finch
wintry quarry
rich adder
ivory bobcat
buoyant finch
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ECM.Components;
using ECM.Walkthrough.MovementRelativeToCamera;

public class PokemonWalkCycle : MonoBehaviour
{
[SerializeField]
MeshFilter mf;

[SerializeField]
float timer, timerMax;

Mesh mesh;

[SerializeField]
Mesh[] meshes;

[SerializeField]
int meshCount;

[SerializeField]
MyCharacterController mcc;

[SerializeField]
Rigidbody rb;

bool moving;

// Start is called before the first frame update
void Start()
{
    mesh = mf.mesh;
    meshCount = 0;
    moving = false;
}

// Update is called once per frame
void Update()
{
    if (rb.velocity.magnitude > 0)
    {
        moving = true;
    }
    else
    {
        moving = false;
    }

    if (moving)
    {

        if (timer > timerMax)
        {
            mf.mesh = meshes[meshCount];

            meshCount++;

            if (meshCount >= meshes.Length)
            {
                meshCount = 0;
            }

            timer = 0;
        }
        else
        {
            timer += Time.deltaTime;
        }
    }
    else
    {
        mf.mesh = meshes[0];
    }

}

}
this is the code

eternal falconBOT
rich adder
#

also using ECM.Components; 😵‍💫

buoyant finch
#

ye it is easy character controller basically a character controller

rich adder
#

why are u mixing two controllers

#

mcc its unused anyway ig

buoyant finch
rich adder
#

please format the code at least

buoyant finch
#

it is on

median stream
rich adder
#

is this what follows player ? doesnt do anything it seems @buoyant finch

wintry quarry
buoyant finch
rich adder
#

why are showing this then ?

buoyant finch
rich adder
#

we asked for the implementation you currently have for follow

wintry quarry
# median stream this tutorial

Clearly the isWallJumping bool is not in and of itself the right indicator to decide when to flip your character. You want to flip them when you jump off the wall, right? Do it then and not in Update.

buoyant finch
median stream
#

but he did it in update

#

so i am not sure

wintry quarry
#

It's nothing like yours

rich adder
median stream
#

so where should i call it?

wintry quarry
rich adder
wintry quarry
rich adder
#

slowly fix the issue of being directly behind

buoyant finch
median stream
#

mine also has

rich adder
#

you probably at some point might need figure out if you need a DOT product

median stream
hallow bridge
#

Does Unity automatically unroll loops and if not is there a way to make it do it automatically without doing it manually?

median stream
#

@wintry quarry UnityChanHuh

wintry quarry
#

the real answer is to think about what your code is doing and reconcile how this flip logic works and call it appropriately as needed.

west sonnet
#

With the way this is set up, "TurnAround" goes back to false after it's turned to true, because the gameobject turns around, mean the "detection.collider" is null. Anyone know how I can keep the bool true?

wintry quarry
#

we don't jknow how those variables are used, or why they're even needed

#

Is there a reason you need this TurnAround variable at all? WHy not just flip the character right then and there?

west sonnet
#

I need to flip the character and make them move in the opposite direction

wintry quarry
#

Why not just make a Flip() function that does just that, and call it here

west sonnet
wintry quarry
#

That doesn't make a lot of sense to me

west sonnet
#

Because I'm using bools to determine which way the character should move

wintry quarry
#

You're overcomplicating it my friend

median stream
wintry quarry
#

Simple

#

if you want a bool for facing left/right and different speeds?

Vector3 moveDirection = Vector3.right;
float speed;
bool runningAway = false;

void Flip() {
  moveDirection *= -1;
  NakedManSprite.flipX = !NakedManSprite.flipX;
  facingRight = !facingRight;
  speed = runningAway ? RunAwaySpeed : NormalSpeed;
}

void Update() {
  transform.Translate(moveDirection * speed * Time.deltaTime);

  // Raycast here
  if (detection.collider != null) {
    Flip();
  }
}```
west sonnet
#

speed = runningAway ? RunAwaySpeed : NormalSpeed;

What do the "?" and ":" do?

wintry quarry
#

it's saying "if runningAway use RunAwaySpeed. Otherwise NormalSpeed"

west sonnet
#

aahhh okay, thanks

languid spire
swift crag
#

it's the only ternary operator in C#!

#

(hence it's often just called a "ternary")

#

it has three arguments. compare this to the more common unary (1 thing) and binary (2 things) operators

#

-3 is unary minus; 1 + 5 is binary plus

brazen mortar
#

hey I just want to check I'm understanding a particularly stupid bug correctly: the screenshotted code was intended to set occupied to true if worker.myHex is equal to hex. Is it correct that what it actually does is sets worker.myHex = hex, then returns true if it did so successfully?

long tiger
#

hey yall im having a weird issue with my character movement, every time i want him to jump he just goes flying whenever i hold down the space bar. here's the code anyone know whats the issue?

here's the code

(its a 2D platformer with a 3D model for reference)

public class PlayerMovement : MonoBehaviour
{
    int moveSpeed = 10;
    int jumpForce = 5;
    public void Update()
    {
        if (Input.GetKey(KeyCode.D))
        {
            GetComponent<Animator>().SetBool("RunForward", true);
            GetComponent<Animator>().SetBool("Idle", false);
            moveSpeed = 10;
            transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed);

        }
        if (Input.GetKey(KeyCode.A))
        {
            GetComponent<Animator>().SetBool("WalkBack", true);
            GetComponent<Animator>().SetBool("Idle", false);
            moveSpeed = 5;
            transform.Translate(Vector3.back * Time.deltaTime * moveSpeed);

        }
        if (Input.GetKey(KeyCode.Space))
        {
            GetComponent<Animator>().SetTrigger("Jump");
            GetComponent<Rigidbody>().AddForce(Vector2.up * jumpForce);
        }
wintry quarry
#

= is assignment

swift crag
#

it doesn't return a boolean, and it definitely can't "fail"

swift crag
#

so yes, your description is correct

#

i'm assuming worker.myhex is not a bool

brazen mortar
#

yes

swift crag
#

however, if it's a unity object, it can implicitly convert to a bool

#

so your code assigns hex to worker.myhex, then runs the following block if hex is a valid unity object

brazen mortar
#

cool, thanks

swift crag
#

(assuming hex is a unity object here)

#

otherwise it's probably going to be a compile error because that's not a bool

languid spire
brazen mortar
#

yeah, I just found that missing =, which was causing two different weird behaviors and got curious about how exactly that incorrect code was being read

swift crag
brazen mortar
#

that explanation was in fact what I was looking for

languid spire
brazen mortar
#

sir i am right here

#

i mean that jokingly

willow scroll
tranquil hollow
#

why some times i need spam space to my player jump? is it a delay?

swift crag
#

there are a few possibilities

#

!code

eternal falconBOT
tranquil hollow
#

ok

swift crag
#

indeed (:

wintry quarry
swift crag
#

nooo my reply

wintry quarry
#

input should only be read in Update

languid gyro
#

anyone knows how to make an IRL timer for the skyboxes?

wintry quarry
swift crag
languid gyro
#

ok?

#

let me find it on unity doc

swift crag
#

It's going to be in the C# documentation.

#

You can ask DateTime for things like "what hour is it?"

wintry quarry
#

Basically:
double normalizedTimeOfDay = DateTime.Now.TimeOfDay.TotalHours / 24.0;

#

gives you a 0-1 value for current time of day, where 0 and 1 are midnight and 0.5 is noon

wintry quarry
#

Or actually I guess you can just use:
double normalizedTimeOfDay = DateTime.Now.TimeOfDay.TotalDays;

tranquil hollow
wintry quarry
#

so it's not that helpful to us

#

we're concerned about when you jump not how you jump

#

i.e. we care about when Jump is called

tranquil hollow
#
    void FixedUpdate()
    {
        Move();
        Attack();


        if(isGrounded == true)
        {
            addJumps = 1;
            if (Input.GetButtonDown("Jump"))
            {
                Jump();
            }
    }
    else
    {
        if(Input.GetButtonDown("Jump") && addJumps > 0)
        {
            addJumps--;
            Jump();
        }
    }
#

that one?

wintry quarry
#

right so exactly like I said

#

You're reading input in FixedUpdate

#

and input should only be read in Update

#

otherwise you will miss input, as you are seeing.

swift crag
#

it's because Input.GetButtonDown is true for one frame

#

but FixedUpdate can run any number of times per frame (including zero)

tranquil hollow
swift crag
#

re-read praetor's post

wintry quarry
#

Move your input handling to Update of course

swift crag
#

at a high framerate, you'll have many frames between each FixedUpdate, so most of your inputs will get missed if you check them in FixedUpdate

teal charm
teal charm
#

you should jump only when the player is on the ground

brazen mortar
wintry quarry
long tiger
#

i see

#

ok so i changed it to transform.translate movement to match the rest but now it just teleports the player upwards instead of a normal jump

#
 if (Input.GetKeyDown(KeyCode.Space))
 {
     GetComponent<Animator>().SetTrigger("Jump");
     transform.Translate(Vector2.up * jumpForce);
 }
wintry quarry
#

If you want physics, use physics

#

otherwise, you have to do everything yourself

brazen canyon
#

Excuse me why can't I insert elements in this SO ?

tranquil hollow
#

like this?

wintry quarry
#

sure

tranquil hollow
wintry quarry
#

probably mismatched brackets or something

#

Can't tell you more without seeing the code

willow scroll
#

You can write it once and check the boolean in it

tranquil hollow
#

it worked, tysm guys 😄

languid spire
brazen canyon
languid spire
brazen canyon
brazen canyon
languid spire
#

then you cannot override you can only change or replace the original

distant hawk
#

Monster

brave robin
#

If you want B to modify that array, you'd need public methods in A for doing so. Like SetArray(int x, int y, int value) { }

languid spire
#

And if you want B to have it's own copy of the array you would need to clone it by using someting like BlockCopy

brave robin
languid spire
willow scroll
brave robin
willow scroll
#

It's still pretty uncomfortable if done this way

brave robin
#

Sure, but when the constraints prevent a multidimensional array or jagged array then this is one alternative

median stream
#

this is the code i am using

languid spire
#

@brazen canyon If you want a 2d array editable in the inspector

class MySo : ScriptableObject {
public MyStruct[] myStructs;
}
[Serializable]
public struct MyStruct {
public int[] myInts;
}
willow scroll
# median stream

Please, consider sending huge code blocks using one of the sites listed below !code

eternal falconBOT
brazen canyon
willow scroll
brazen canyon
median stream
willow scroll
brazen canyon
#

Yeah ...
That's what I sound like when I went crazy

median stream
#

here is another code for physics stuff

#

is there any way you can help me with this one?

#

or should i just change my whole code for wall jump

late burrow
#

string split is easy way of getting variables from text but is it good for large files

#

maybe there better ways

wintry quarry
#

no string split is not a good way

late burrow
#

so what would be better

wintry quarry
#

it depends what kind of information and what file format we're talking about

late burrow
#

just text file

wintry quarry
#

that is meaningless

#

what format is the text in

#

what information are you trying to get from it?

#

json is "just a text file"

#

but you'd use a Json parser for it

willow scroll
late burrow
#

vector positions, times,

#

like 1000 lines of that

late burrow
#

each with same info

willow scroll
median stream
#

and some time the front face get inverted

late burrow
#

what if i want do stuff manually

willow scroll
wintry quarry
late burrow
#

so basically what i was doing most of time

languid spire
wintry quarry
late burrow
#

just i guess if i predefine specific function to each line it will perform better

#

at the cost of no futher compatibility

wintry quarry
#

at a basic level a parser should be a state machine

#

you are always expecting some kind of input in each state

blazing warren
#

Would it be improper or unnecessary to add data to gameObjects using scripts? So for example, if I want a gameObject to be considered "deformable", would I make a script called "isDeformable" which has nothing in it except fields like deformRadius and deformMagnitude, and attach it to the object?

eternal needle
languid spire
willow scroll
# late burrow so basically what i was doing most of time

The reason why you cannot move is, probably, because of your isWalljumping value not being properly assigned, as you're checking for it before moving

if (!isWalljumping)
    controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
brave robin
blazing warren
#

Okay, sweet. I'm looking to getComponent it only upon collision enter, which in my circumstance won't be called often

willow scroll
#

Yes, you should assign it correctly

#

Let me have a look at it

#

So, isWallJumping depends on wallJumpingCounter and isWallSliding

willow scroll
#

Pretty hard to say without debugging

#

isWallJumping is just set to true when wallJumpingCounter > 0f

#

And then it's set to 0f, which makes isWallJumping not be able to be set to true again

#

walJumpingCounter is just increased when isWallSliding

median stream
# willow scroll And then it's set to `0f`, which makes `isWallJumping` not be able to be set to ...

i am also not sure either 😭 is just try to follow this tutorialhttps://youtu.be/O6VX6Ro7EtA?si=-zIn3cJFi2k5GIdx

willow scroll
#

So have you just copied the code from there?

median stream
median stream
willow scroll
#

Well, can isWallSliding even be true for a single frame?

#

It's set to false in WallJump right after it's set to true in WallSlide

#

Oh, this might be it

median stream
median stream
willow scroll
#

Let me think how to start

#

There is this line, which invokes the method StopWallJumping after a certain amount of seconds

Invoke(nameof(StopWallJumping), wallJumpingDuration);
#

This method is the only one which sets isWallJumping to false

private void StopWallJumping()
{
    isWalljumping = false;
}
#

Which makes the player be able to move, as there is a condition for it

#

But if isWallSliding is true, isWallSliding is set to false and the method gets cancelled.

CancelInvoke(nameof(StopWallJumping));

This way, isWallJumping is not set to false

#

The boolean can be updated just when the Jump key is pressed

#

But if isWallSliding is true the next frame, it doesn't update the boolean, assuming your Updaste runs more often than 2.5 times per second

#

That's the condition, which assigns isWallSliding to true

if (IsWalled() && !controller.m_Grounded && horizontalMove !=0f) 
#

Although, horizontalMove is, probably, 0

#

And that's the only place isWallSliding is assigned to true

#

Anyway, you gotta check out those booleans and see

#

As I have previously mentioned, hard to say without debugging, as for me

median stream
#

oky.... ill try my best to fix it this explain a lot of things thanks for your help 😄

willow scroll
median stream
chrome chasm
#

How can I change a PP volume's value in code? I tried this but didn't work:

    public void EnableCameraBlur()
    {
        if (m_CameraVolume.profile.TryGetSettings(out DepthOfField depthOfField))
        {
            FloatParameter param = new FloatParameter();
            param.value = 0.1f;
            depthOfField.focalLength = param;
        }
    }
swift crag
#

You need to modify the exisitng parameter.

#

replacing it means that other code is looking at the old float parameter

chrome chasm
#

I can't directly set focalLength to a float value because it's of type FloatParameter

swift crag
#

right, so set flocalLength.value = ...

chrome chasm
#

oh pff of course -.-

#

my bad xD

wet nebula
#

Hello guys! I`m doing a FSM and I have a EnemyFactory to store all the states available, like this image. I want to create StateFactory to derive from the base and use it in the Manager, but when I do, the IDE says the State does not exist. But if I create it in BaseFactory and override it in the child, still does not work. :/

Any ideas? Thanks a lot!

wintry quarry
#

but based on your diagram

#

it seems like you have a variable of type EnemyStateFactory which wouldn't have a "Runaway" field

wet nebula
#

I don't know if it is enough 😅

#

I don't even know if I am doing it the best way, I just wanted to create a baseFactory that I could override with the States needed.

E.g. The RunawayState becomes the RunState with the override

brave robin
queen adder
#

its stuck on applcation.enterplaymode ?

wet nebula
swift crag
#

I don't know what you're referring to in your original question. you need to show us the actual problem

#

the IDE says the State does not exist

brave robin
wet nebula
swift crag
#

Show the code that produced the error.

wet nebula
swift crag
#

If you want to access members from a derived class, you must downcast to that class.

#

This usually indicates that you have a design problem

polar acorn
swift crag
#

You want to use polymorphism so that different kinds of enemies can do different things

#

instead of directly telling the enemy "go into the Runaway state!", perhaps you should be able to say "hey, you got startled!"

#

different kinds of enemies can respond differently

#

also, this factory appears to do nothing

wet nebula
brave robin
# wet nebula

Enemy doesn't have Runaway, FugitiveEnemy does. So you must make a new temp variable that is fugitiveEnemy as FugitiveEnemy and then you'll have access to it. That new temp var will be null if the enemy is not derived from FugitiveEnemy, so check that before using it

wintry quarry
# wet nebula

why not like a Dictionary<string, BaseState> then you can just make a function like enemy.GetState("Runaway")

swift crag
#

if you do want to downcast:

if (enemy is FugitiveEnemy fugitiveEnemy) {
  fugitiveEnemy.DoSomethingSpecific();
}
#

this combines the cast and the validity check

brave robin
#

Even better

wet nebula
wet nebula
wintry quarry
brave robin
#

Giftcard scambot detected

#

That was deleted fast

wet nebula
swift crag
#

i'm not sure you understand what you're doing here...

wintry quarry
swift crag
#

i don't see a reason to have factories and all sorts of other contraptions

wintry quarry
#

But yeah this is like
Someone read a "Best practices for enterprise Java" book from 1998 and tried to apply the practices to Unity in 2024

swift crag
#

just make multiple kinds of enemies that have some common methods in their parent class

#

Startle(), for example

#

a RunawayEnemy can respond by fleeing

#

a CombatEnemy can respond by shooting at you

wet nebula
primal narwhal
#

if I build my game, will playerprefs still work?

brave robin
wet nebula
#

So much that I can't even explain to you guys 😅

brave robin
#

Having multiple enemy classes is fine, but the decision making for each enemy type needs to be self contained in each class. So when an outside manager class tells an enemy to act, it doesn't need to know what type of enemy it is. It just operates on methods that are in the base class, and anything unique to the child classes isn't something the manager class ever touches

snow girder
#

why doesn't this play the sound

swift crag
wintry quarry
wintry quarry
swift crag
wintry quarry
#

so of course it won't play

snow girder
swift crag
#

you just said "Destroy this game object"

wintry quarry
brave robin
#

Nope, its starting to play and then is being destroyed in the same frame

snow girder
#

ah damn

#

i see

wintry quarry
#

Destroy has a second parameter

#

which is a delay

#

you could use that

brave robin
#

"who killed hannibal" meme, essentially 🙂

snow girder
#

once more i am stupid

brave robin
summer summit
#

Running into a weird issue. Not particularly familiar with Unity yet so I thought i'd check. I'm trying to attach a script to a gameobject (probably the camera), but I can't even get a "hello world" output to work on the "Awake()" or "Start()" functions. "Update()" will output the Debug.log statements I added in, but the other two functions don't seem to be called at all. I ran through a lot of the suggested checks, but nothing seems to be working. Am i missing something?

#

Also Hi

swift crag
#

Show your code.

#

!code

eternal falconBOT
wintry quarry
summer summit
#

I had other stuff but it's literally barebones now. Sure one sec.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestAwakeStart : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Starting Start in Test Script!");
        print("Printing Start in Test Script!");

    }
    void Awake()
    {
        Debug.Log("Starting Awake in Test Script!");
        print("Printing Awake in Test Script!");
    }
    // Update is called once per frame
    void Update()
    {
        Debug.Log("Updated");
    }
}

#

no compiler errors

wintry quarry
brave robin
#

Are you using AddComponent at runtime to give the camera that script?

summer summit
#

yep it's saved. I've tried multiple variations. Like I said the "updated" output posts to the console when I build the app, but the start/awake functions don't.

I just dragged the script onto the camera (and checked that it's enabled)

#

Not even getting warnings in the console when its' running

wintry quarry
#

please share the screenshot(s)

brave robin
#

Yeah, I thimk maybe you didn't save changes to the script, like PraetorBlue mentioned

#

and so you're testing with an older version htat doesn't have awake and start in it with the debug logs

summer summit
#

just stuff like this

swift crag
#

or the tidal wave of "Updated" is washing away the messages

wintry quarry
wintry quarry
#

how do you know this isn't printed?

#

It's probably near the beginning

summer summit
#

Definitely saved changes to the script, because I've tried removing the "updated" output and putting it back in, and the changes were reflected when I built the app. I checked the beginning, and also did a search through the logs. For example I can search for "updated" and it will come up in the console. But searching for "awake" will come up with nothing

#

hang on i'll comment it out and recompile it to clean up the console if you want

swift crag
#

This is being tested remotely on a headset, right?

#

I wonder if you miss the first frame's messages.

#

Consider the following:

IEnumerator Start() {
  yield return new WaitForSeconds(1f);
  print("Start!");
}
#

replace your Start method with this and observe how it behaves

summer summit
#

Yeah I'm testing it directly on my quest 3. It's going to be a MR app

#

hmm, if I check "wait for managed debugger" in the build settings would that cover it?

swift crag
#

I'm not familiar with remote debugging/playing in general

#

i believe you'd only want that if you were doing actual script debugging

summer summit
#

Well I seem to recall that if i didn't have "script debugging" checked I wasn't getting any messages in the console at all that I put out

#

Hmm maybe if Initiailize a variable or something in the start and then output it in updated it will tell me if it's getting run

summer summit
#

i was getting a compiler error. Something about not being able to do it with a void function?

swift crag
#

replace the entire Start method with the code I provided

#

note how it returns IEnumerator, not void

summer summit
#

Aha they are getting run apparently...

#

I tried the other method first since I was in the middle of it

#

i set the value for a variable in each of them, then outputted the variable in "updated"

#

it's showing both are apparently running, they just weren't giving me any actual output

scarlet skiff
#

how does one pass a reference to an object in the scene to a prefab but the prefab is the player and istn spawner via a spawner than u could just pass down the reference from there, the player is netwrok object that spawns in via thew netwrok manager whne a client connects

summer summit
#

so weird

#

brb

wintry quarry
swift crag
scarlet skiff
# wintry quarry What object do you need a reference to?

the health bar, i know a solution is to just spawn a canvas with the health bar, like have it as a part of the player prefab but i feel liek thats messy, if i just run the players health script locally it should also work?

wintry quarry
#

but yeah you can have it as part of the player prefab

scarlet skiff
wintry quarry
#

also a healthj bar definitely isn't something that needs to be networked

wintry quarry
#

Or is it a health bar floating on a player's head or something? Or what

scarlet skiff
#

so yes only one of it

wintry quarry
swift crag
#

yeah, since it's a trivial thing to find

#

You have to start worrying if you have multiple things you could find

wintry quarry
#

it definitely should be a local client only thing

swift crag
#

(and only one of them is right)

scarlet skiff
#

well.. tag is easier but i dont want a tag just for that

#

so ill go with singleton?

scarlet skiff
wintry quarry
#

You have "I don't want to do that" to every other solution so why not.

wintry quarry
scarlet skiff
#

oh boy.. even more new stuff that i have to get to know

swift crag
#

you're making a multiplayer game

#

you'll be experiencing this a lot (:

wintry quarry
#

Yeaaa.... to be honest if you haven't mastered juggling references yet, I wouldn't be dabbling in multiplayer, but that's just me.

chrome chasm
#

I'm trying to exclude certain items from my post processing layer (for when you examine an item) so I made a child camera on my main camera which renders a seperate layer for certain objects and set the Clear Flags to Don't clear. Problem is that the entire item is not visible anymore.

wintry quarry
chrome chasm
#

ah that was the problem

#

thanks!

hasty spire
swift crag
#

there is one, and only one, cause for a null reference exception

#

something on that line is null

hasty spire
#

so either volumeSliderValue is null or AudioManager,instance.masterVolume is null

swift crag
#

AudioManager.instance could be null.

hasty spire
#

the other one can't be null volumeSliderValue

swift crag
#

even if it was a reference-typed variable that could be null, it wouldn't matter -- you're just assigning something into it

#
string whatever = null;
whatever = "hi";
tame mist
#

i put a cylinder in my game scene that i'm going to use as like a wheel of fortune board.
the problem i'm having is that it seems like the rotation is clamped from -180 to 180.
why is this happening?
also here is the current code i'm using in an update function:

// Calculate the rotation angle
float rotationAngle = rotationSpeed * Time.deltaTime;

// Apply rotation to the object's local rotation
transform.localRotation *= Quaternion.Euler(rotationAngle, 0f, 0f);
hasty spire
#

if i added an if statement checking if audio manager is null would that fix things?

swift crag
#

you have a problem when you try to use the member access operator on a null reference!

foo.bar.baz

foo or bar being null here would trigger an exception