#💻┃code-beginner

1 messages · Page 380 of 1

next ravine
#

oh no

kindred pollen
#

is it alright if i dm you? i'm still kinda lost but dont want to flood the chat.

swift crag
polar acorn
next ravine
#

i cant in this situation

swift crag
#

Why?

#

here comes the XY problem...

lethal bolt
#

Is there a way around it?

polar acorn
#

Then that would mean that you'd be facing diagnoally

polar acorn
lethal bolt
polar acorn
#

A transform is not a vector. We've been through this

#

You can't set a transform to a vector

lethal bolt
#

oh

#

why..

#

it would be so usefull

polar acorn
swift crag
#

why can't I assign a Banana into an Apple variable?

lethal bolt
swift crag
#

both are edible

polar acorn
#

If someone asked for a picture of my cat and I sent them a jpg of a coconut that would not be what they requested

lethal bolt
#

Exactly

polar acorn
#

Vectors don't have positions

swift crag
#

it wouldn't even do anything useful

polar acorn
#

Vectors are positions

swift crag
#

you'd be just...replacing your Transform reference

polar acorn
#

Transform has a property .position. Vectors do not

lethal bolt
#

Mby

swift crag
#

with a new, bogus reference to the wrong type entirely

swift crag
#

were you trying to do something like this?

polar acorn
swift crag
#
public Vector3 spawn = new Vector3(0, PlayPos.y, 0);
polar acorn
#

"Bananas come from trees so why can't I eat the tree?"

lethal bolt
#

Why cant i put an float in there tho

polar acorn
lethal bolt
#

In the X axis

polar acorn
#

Does your camera rotate with your player?

swift crag
polar acorn
# lethal bolt In the X axis

You can, just not outside a method. You can't put Speed in there because Speed doesn't actually exist yet. All of those variables get created at the same time

swift crag
#

Did you try to do new Vector3(1.5, 0, 0); ?

polar acorn
#

In Start for example, you could change spawn to a value including Speed

lethal bolt
#

But i want the cube to spawn at (PlayPos + 10, 0, 0)

#

But that isnt possible so i need to use NEw vector

polar acorn
#

While playing, click the player again and see what direction the blue arrow is pointing. That is the direction your player will move when you press W.

swift crag
polar acorn
swift crag
#

Just calculate it in Start.

polar acorn
#

Spawn the cube at that position

#

Nothing in this code spawns a cube though

lethal bolt
#

No but this is the move script

#

i have the cube in the scene

polar acorn
#

Look at where you're spawning it instead

rich adder
neon marlin
#

it works but it's like some directions are swapped?

lethal bolt
swift crag
neon marlin
#

oh my god

#

yes

swift crag
#

You can fix this by adding a 90 degree rotation

polar acorn
#

Can you show the updated code?

timber tide
#

was working with some opengl library earlier and it was expecting me to label all integers and zeroes as float despite it only using float anyway

neon marlin
#

thanks that was a dumb mistake my bad

swift crag
#
Quaternion.AngleAxis(90, Vector3.forward) * someOtherRotation
polar acorn
#

Can you show the inspector for this object?

lethal bolt
#

Yes. Not yet i only focuse on where it should spawn not the spawning

modest dust
#

When spawning get the player position and add your offset

lethal bolt
#

But i want the x to be set to an float -10

polar acorn
modest dust
polar acorn
#

There does not seem to be any scripts in this screenshot

swift crag
#

add spawn to another vector

#

or just set the x component of spawn before you use it

polar acorn
#

Okay, so your speed is positive, meaning W should be moving you in the direction of this blue arrow. That is, away from the back wall. Is that not what's happening? Note that your camera does not appear to be facing in this direction, so you'd be moving to the side of your camera from the looks of it

swift crag
#

interpolation can smooth out rigidbody movement

polar acorn
#

The code you shared would move this object in the direction of the blue arrow whenever you press W. If that is not what you are seeing then there is something else affecting it.

lethal bolt
#

Now that it works. How can i set the PlayPos to the position of the player?!

astral falcon
#

you guys are still here? Impressive 😄

polar acorn
#

Drag in the object you want PlayerPos to refer to

lethal bolt
#

Ye but then i cant set it in the X on the "Transform.poistion"

lethal bolt
#

Because i thougth i coulndt mix Vector and transform

polar acorn
lethal bolt
#

Yes?

polar acorn
#

transform.position is a vector

#

Transform is not a vector

#

It has a vector property named transform

lethal bolt
#

See, red?

polar acorn
#

This would rotate the object, but your movement would still be in the direction of the blue arrow

polar acorn
lethal bolt
#

So how can i set The X axis to the player's x axis ?

polar acorn
#

Instead of the whole ass transform

#

I don't know what else is in your project. If the code you've shown is what you're running, then pressing W will move whatever object gracz is in the direction of this object's blue arrow

#

If that isn't happening, something else is moving it in a different direction

#

And nothing you've posted would do that either

verbal dome
#

You still have this weird -90 degree angle offset in your camera script

lethal bolt
verbal dome
#

Camera is child of gracz (which is the player?) and has its own local rotation

polar acorn
verbal dome
#

So the camera's rotation will be player rotation PLUS camera rotation, right

#

Doesn't sound right

lethal bolt
#

or smlt

verbal dome
#

Is the camera selected in this video?

lethal bolt
#

But how can i do it with an variable?

vernal holly
#

Can someone help me figure out why is this not working? the player will not get deleted when it enters the box

lethal bolt
#

Or is that even possible

polar acorn
lethal bolt
#

yes

wintry quarry
polar acorn
verbal dome
#

What if you remove this line: MouseX = -90f; from the camera script?

languid spire
# lethal bolt yes

Instead of all this 20 questions. Why don't you go and look at the Transform documentation?

verbal dome
#

What if you change graczcam.localRotation = to gracszcam.rotation =

vernal holly
lethal bolt
#

Thanks @polar acorn (:

robust kelp
#

when i click start in unity editor and hold lctrl and click outside of the game view unity keeps the value from when i pressed it and makes it the unpressed value should i worry about that?

vernal holly
wintry quarry
vernal holly
wintry quarry
#

it doesn't happen magically

polar acorn
wintry quarry
polar acorn
vernal holly
wintry quarry
polar acorn
verbal dome
#

Post both full scripts in a paste site !code

eternal falconBOT
vernal holly
polar acorn
#

Oh wait hang on

verbal dome
#

So it's a trigger but youre using OnCollisionEnter2D? Or did I miss something

polar acorn
#

I've missed a very obvious problem

verbal dome
#

You even asked if it's a trigger 😄

#

Which made me notice

#

Your z and x are flipped

#

In ruch script

#

ruch

polar acorn
#

How did I miss that

late burrow
#

how i treat struct as string for its default value

short hazel
#

huh

late burrow
#

i know i can alter what it prints by overriding tostring

buoyant knot
#

you mean like an implicit cast?

late burrow
#

but not directly getting

#

i want indexof using string on my struct

vernal holly
short hazel
buoyant knot
#

i would just use ToString().IndexOf()

#

don’t overcomplicate your struct with shit it doesn’t need

late burrow
#
holder.IndexOf("test");```
#

like this

#

i want get while not holding custom variable

#

it holds many more values

polar acorn
short hazel
#

So, an implicit conversion from string to custom?

polar acorn
#

unless custom is a subclass of string I guess?

languid spire
late burrow
#

yes i want it to be treated as string by default but also store variables inside itself

buoyant knot
#

i would recommend you not implicitly cast with string unless you have a really good reason to

#

because this isn’t going to work the way you think it will

short hazel
late burrow
#

not object?

#

something thats universal

short hazel
#

What are you trying to solve here

#

Talk about your issue, not how you're trying to solve it

slender nymph
#

maybe someday anuked will not try to use strings for literally everything. but it does not seem like that day is today

late burrow
#

getting custom variable without custom variable in hand

buoyant knot
#

using strings for that is bad juju

#

it will fuck you up. your teeth will rot, and your hair will fall out.

short hazel
#

and the compiler will yell at you

late burrow
#

since it feels worse to create new struct out of string just to compare it in list

buoyant knot
#

you have a deeper problem here, tbh

short hazel
#

Just use a List<string>? I don't get the issue (is there even an issue to begin with?)

late burrow
#

im rewriting it for the third time since when i did one thing it didnt matched the other

#

so im looking for universal storage

buoyant knot
#

that is not how this is going to go down

#

trying to get variables by strings is really bad

late burrow
buoyant knot
#

you should be using objects with specific references to other objects

#

the closest you might need is a singleton, where you can get a reference to the unique instance of a given class

late burrow
#

im basically looking for mix of class and interface

#

so i can do everything in it

buoyant knot
#

but at this stage, i fear your inexperience will cause you to spam singletons unnecessarily

languid spire
polar acorn
#

You're just kind of vomiting random keywords

buoyant knot
#

you can do it. But you really should not.

short hazel
#

My brain is having a real hard time understanding that, does anyone have a transpiler??

late burrow
#

class part of storing any amount of variables in it and interface part of treating object itself as another var as well

buoyant knot
polar acorn
buoyant knot
#

so it is understandable in a sense.

short hazel
late burrow
#

though i can just use tostring.indexof fine

polar acorn
short hazel
#

It's not going to work. Doing .ToString() on a List<Thing> is going to give you the string "List'1[Thing]" literally, and using IndexOf() on that is pretty much nonsense

outer coral
#

He is most definitely just trolling

buoyant knot
late burrow
#

a yeah i probably wanted to use that

#

just forgot the function as i was using dictionaries so much

verbal dome
#

Something like holder.FindIndex(item => item.someString == "test")

frank zodiac
#
for (int i = 0; i < 15; i++)
{
    StartCoroutine(WaitForSeconds(1.5f));
    Instantiate(enemy1Prefab, new Vector2(9.5f, Random.Range(-2.5f, 2.5f)), Quaternion.identity);
}

IEnumerator WaitForSeconds(float secondsToWait)
{
    yield return new WaitForSeconds(secondsToWait);
}
``` is there anything wrong with this code? because its not working for me. its supposed to spawn an enemy every 1.5 seconds, but instead it just spawns them ALL at once
outer coral
#

You need to spawn them in the coroutine

buoyant knot
#

i must pray for him. his inability to write basic english gives me no confidence that his spelling will be what a string=>ref system demands.

frank zodiac
short hazel
late burrow
#

that but adding variables that i cannot create

#

so i wanted use string to find a struct

frank zodiac
# outer coral You need to spawn them in the coroutine
{
    for (int i = 0; i < 15; i++)
    {
        StartCoroutine(Wave1());
    }
}

IEnumerator Wave1()
{
    Instantiate(enemy1Prefab, new Vector2(9.5f, Random.Range(-2.5f, 2.5f)), Quaternion.identity);
    yield return new WaitForSeconds(1.5f);
}```like this?
late burrow
#

or more like getting as finding is bad idea considering im running loop inside a loop already

buoyant knot
short hazel
#

With a mix of class and interface

outer coral
buoyant knot
#

Interface classes with index and list, but with indexof string and Turing Completeness.

frank zodiac
buoyant knot
#

ok i’m done. even if it was warranted

late burrow
#

ok about this one i can go more detailed

i have a struct, each struct holds reference to array of all other structs, struct also holds block of data which can be got as string, and this string holds array of strings from different structs of same type which already exist in array

and question was how to get these sub structs using a string, but if there aint good way i will just do a loop comparing strings each time i need them or something

upper yoke
#

Hey, I'm trying to do a simple raycast:

var hit = Physics2D.Raycast(transform.position, attackDir, 100f, _targettingLayer);

And I have this debug:

Debug.Log($"00000 {hit.point} == {hit.collider.transform.position}");

Which gives me this:

00000 (-4.00, 0.00) == (1.00, 3.37, 0.00)

However the 2 points are quite far away (first element is green circle and 2nd red circle) and I can't figure out why? (The green point should be ignored by the layer)
I'm on Unity 6000.0.5f1

short hazel
#

_targettingLayer is a layer mask, right? Not a single layer index

#

Also show how you calculate attackDir

winter spade
#

whats a good c# IDE u can recommend to a beginner?

upper yoke
#

Yup

        _targettingLayer = 1 << LayerMask.NameToLayer("Wall");
        _targettingLayer |= 1 << LayerMask.NameToLayer("Enemy");
var attackDir = closest.transform.position - transform.position;
upper yoke
#

ah

wintry quarry
#

Well

#

Actually it's ok but unnecessarily complicated

#

Use LayerMask.GetMask("Wall", "Enemy")

timber tide
#

looks like my code :)

wintry quarry
#

Sorry I jumped because I saw nametolayer

short hazel
#

Create a public LayerMask field, and Unity will make a nice dropdown in the Inspector, as an alternative

timber tide
#

I usually have my own layer utility class that'll give layers/masks an enum type

upper yoke
#

My code is a bit cleaner now but I still have the same issue

rocky canyon
wintry quarry
#

One thing to check first is to make sure you're hitting the object you expect

#

Print the name

upper yoke
#

ah wait yeah, it collides with trigger colliders too right?

rocky canyon
#

yes, this no need to spend time guessing.. full debugs loggin the collision, the collider, name, the time or w/e is the best start

rocky canyon
upper yoke
#

🤔

winter spade
rocky canyon
wintry quarry
#

Print the object name

rocky canyon
#

VStudio community is easier to use for a beginner

#

but im starting to like VSCode better

winter spade
#

whjy?

rocky canyon
#

i personally like the UI better

timber tide
#

vscode so clean

rocky canyon
#

and ive grown pretty dependent on abunch of extensions i use

rocky canyon
#

thought u needed to apply a contactfilter but not the case

upper yoke
#

That explains things a lot, thanks to both of you for your help!

rocky canyon
#

yea, debug the name of the collisions 👍 it'd be helpful most times

rocky canyon
# winter spade whjy?

vscode is a bit more complicated to configure but not too bad, its better now b/c Unity's editor plug-in just works much better

#

and for some reason, i've always had issues w/ Visual Studio Community.. anytime i would rename a file, or move a file from one folder to another.. it'd force open VS and cause editor to have to recompile

#

even if i didn't want to open the script yet

strong wren
#

how do i not show decimal numbers again?

#

i know i need to do smth like ("F1")

#

but idk how i forgot

olive galleon
#

If I want to make a singleton of a player class but have 2 seperate scripts for Player and PlayerMovement how should I approach which script has the singleton?

verbal dome
strong wren
#

oh thank tyou so much

polar acorn
#

Or just cast to int

strong wren
timber tide
#

Also GameManager.Instance.Players[0]

rocky canyon
#

if one references the other u can just use a singleton on the main gameobject, thats how i do

swift crag
rocky canyon
#
player.Instance;
player.Instance.PlayerMovement```
timber tide
#

oh, if it's a single player then playermovement should just be referenced by player ;p

rocky canyon
#

this is how i feel too

winter spade
rocky canyon
#

may be beneficial to learn IDE's in general using VS Comm tho

#

its more user-friendly

strong wren
#
    private int OmrilolPrice = 25;
    public void BuyOmrilol()
    {
        if (Money >= OmrilolPrice)
        {
            Omrilol++;
            MoneyPerSecond += 1;
            Money -= OmrilolPrice;
            OmrilolPrice = Mathf.RoundToInt(OmrilolPrice * 1.35f);
            OmrilolPriceTXT.SetText("Omrilol Price: " + OmrilolPrice);
            OmrilolCounter.SetText("Omrilol: " + Omrilol);
        }
    }```
#

any idea why this code isnt rlly working?

#

i got the money to 10 i click it ajnd nothing happends

polar acorn
#

What calls BuyOmrilol

strong wren
#

oh nvm i found out why it stopped working

hearty perch
#

I've created a separate scene for my Audio Settings with sliders etc.
But now the volume won't change to the correct/saved volume until I go to the Audio Settings scene.
Any way to call for the values from the Main Menu?

strong wren
#

my unity crashed and kinda reset my button

#

i didnt realize

rocky canyon
shell kernel
#

Is there a way to set anim.SetTrigger("die") to false?

slender nymph
#

reset the trigger

rocky canyon
# rocky canyon

MainMenu scene loads in.. and sticks around thru the entire game

slender nymph
rocky canyon
#

is that not what i said? lol thats what i Meant

#

thanks for the eyes 👍

#

ofc. im still undecided what the best way to do it is.. since its a small game.. ive debated on using a gameobject for the main menu

#

but soo far the additive scenes work pretty solid.. and help act as an extra layer of organization

slender nymph
#

their issue can be solved by just loading and applying the saved settings when the game loads instead of only loading when their settings scene loads

rocky canyon
#

true true.. I have temp values.. for when im at teh menu...
when i change the slider i update these values immediately.. (to show the sliders to be accurate)
and then if the user saves.. they get set in the main data.. and modify the audio manager/mixers
if u cancel then the temp values get purged and the sliders all get reset to their default

#

but.. its probably my most complicated system that I've hand-written.. sooo its quite hidious 🤣

hearty perch
#

So I've got this now:

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

public class NewBehaviourScript : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(LoadYourAsyncScene());
    }

    IEnumerator LoadYourAsyncScene()
    {
        AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("AudioSettings");
        while (!asyncLoad.isDone)
        {
            yield return null;
        }
    }
}

It works, like it loads the audio settings, but it also changes the scene to the Audio Settings scene..

hollow dawn
#

quick question do you find this terrifying?

hearty perch
#

And there is a small delay where the sound is a max before it changes it

eternal needle
slender nymph
eternal needle
slender nymph
hearty perch
#

As they are stored in another script / scene

slender nymph
#

well how have you saved the settings

hearty perch
#
public class VolumeSettings : MonoBehaviour
{
   [SerializeField] private AudioMixer myMixer;
   [SerializeField] private Slider masterSlider;
   [SerializeField] private Slider musicSlider;
   [SerializeField] private Slider SFXSlider;

   private void Start()
   {
      if (PlayerPrefs.HasKey("masterVolume"))
      {
         LoadVolume();
      }
      else
      {
         SetMasterVolume();
         SetMusicVolume();
         SetSFXVolume();
      }
   }
   
   public void SetMasterVolume()
   {
      float masterVolume = masterSlider.value;
      myMixer.SetFloat("Master", Mathf.Log10(masterVolume)*20);
      PlayerPrefs.SetFloat("masterVolume", masterVolume);
   }

   public void SetMusicVolume()
   {
      float musicVolume = musicSlider.value;
      myMixer.SetFloat("Music", Mathf.Log10(musicVolume)*20);
      PlayerPrefs.SetFloat("musicVolume", musicVolume);
   }
   
   public void SetSFXVolume()
   {
      float SFXVolume = SFXSlider.value;
      myMixer.SetFloat("SFX", Mathf.Log10(SFXVolume)*20);
      PlayerPrefs.SetFloat("SFXVolume", SFXVolume);
   }

   private void LoadVolume()
   {
      masterSlider.value = PlayerPrefs.GetFloat("masterVolume");
      musicSlider.value = PlayerPrefs.GetFloat("musicVolume");
      SFXSlider.value = PlayerPrefs.GetFloat("SFXVolume");

      SetMasterVolume();
      SetMusicVolume();
      SetSFXVolume();
   }
}
slender nymph
#

so they are saved in PlayerPrefs. so just . . . load them from PlayerPrefs and apply them. maybe even store them in a static class or something

hearty perch
#

I'm having trouble again 😶

#

Do I just copy the entire file or?

#

Cause to apply the PlayerPrefs I would need the SetVolume functions

slender nymph
#

you do not need to set the playerprefs in the main menu, all you need to do is load from PlayerPrefs and apply the loaded value(s) to your mixer(s)

dense root
#

I want to re-call start at the beginning of a battle in my Hiragana learning game. According to my research it's not possible since it can only happen once during a script's lifetime. What's a good way to re-initliaze my whole battle manager at the beginning of a fresh battle?
https://gdl.space/idutekotoj.cs

polar acorn
#

So, you could call Initialize or whatever you call it when a battle restarts

ivory bobcat
#

Or have some public method call start UnityChanHuh

dense root
#

Oh I see, so a good way to go about doing it would be to create a bool isInBattle then use that isInBattle to initiate the desired code

#

Then when the battle is over, set bool to false

polar acorn
hearty perch
# slender nymph you do not need to set the playerprefs in the main menu, all you need to do is *...

I got it to work with this:

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

public class NewBehaviourScript : MonoBehaviour
{
    [SerializeField] private AudioMixer myMixer;
    void Start()
    {
        float masterVolume = PlayerPrefs.GetFloat("masterVolume");
        float musicVolume = PlayerPrefs.GetFloat("musicVolume");
        float SFXVolume = PlayerPrefs.GetFloat("SFXVolume");

        myMixer.SetFloat("Master", Mathf.Log10(masterVolume)*20);
        myMixer.SetFloat("Music", Mathf.Log10(musicVolume)*20);
        myMixer.SetFloat("SFX", Mathf.Log10(SFXVolume)*20);
    }
}

There might be some redundent code but I'm happy it works

#

Thanks for the help Boxfriend

dense root
#

How come my text isn't populating? When I set it manually no issues, but in script it won't populate. Here's a snippet of the call:

void Start()
{
    correctResponse.text = "Wrong!";
}
summer stump
#

Is the correctResponse reference to the right object?

dense root
#

Yeah, that was my first instinct

summer stump
#

You can click it in the inspector and it will highlight the object

#

Hmm, well, then is that object active at runtime, and no other scripts are referencing CorrectResponse text component?

dense root
#

I can double check but I'm pretty sure there isn't

#

Yeah I scrubbed through, nothing to my knowledge is referencing that object

#

Ahh I see what's happening...

#

My rudimentary answer checker is resetting the text on Update, what's a better way to handle the answer check?

private void AnswerCheck()
{
    // This is our answer checker
    if (inputField.text == "あ")
    {
        correctResponse.text = "Correct!";
        // This resets the text field
        inputField.SetTextWithoutNotify("");
        correctResponse.text = "";
        inBattle = false;
        ExitBattle();
    }
    else
    {
        // TODO play a sound
        correctResponse.text = "Wrong!";
        inputField.SetTextWithoutNotify("");
        correctResponse.text = "";
        inBattle = false;
    }
}
#

Hmm maybe when the player presses enter then it calls the answer checker? Rather than it actively checking for the answer

high walrus
#

I have small script for patrolling enemies for my 2d game, but I'm struggling to fix something.
Basically I had the script in void Update() at first, but if I alt-tabbed the position of some enemies would mess up a little. so I then moved the script to void fixedUpdate() and it works perfect now but the movement looks less smooth

#

It's a little hard to see but the first 2 sets of enemies movements look less smooth than the rotating enemies

#

The rotating ones were made in void Update(), the rest are from the script above in void fixedUpdate()

rich adder
eternal falconBOT
swift crag
#

well, yeah, FixedUpdate only runs 50 times per second

#

Even if you don't alt-tab, this will eventually get enemies out of sync when run in Update

#

When an enemy reaches its waypoint, the rest of its movement gets wasted

#

if it can move 1 meter this frame, and only has to move 0.1 meters, the other 0.9 meters are wasted

#

You could fix this by writing a while loop

#

Calculate the enemy's move distance, then use MoveTowards to approach the waypoint

#

Check how far you moved. If you moved less than your move distance, switch to the next waypoint and run the process again

high walrus
#

Gotcha, thanks!

high walrus
swift crag
#

you might want to add a sanity check that breaks the loop after, say, 1000 iterations

#

so that the game doesn't freeze if you mess up

high walrus
#

gotcha, I'll work on that then!

rich adder
high walrus
#

Oh right, that makes sense!

#

Will use that from now on

outer coral
#

Is System.Management not supported?

tried adding with dotnet command in terminal too

rich adder
#

If it's windows only library prob won't see

outer coral
#

its .NET

rich adder
#

I get that

outer coral
#

can i shove the dll in the plugins folder

#

or will that not work

rich adder
#

You could probably just do that if you get a compatible. Net version

round pebble
#

So im not sure if its the animation settings or my code, but im trying to have an enemy walk/idle using a blend tree mixed with a script, but when trying to have him walk, he just plays the idle animation and never plays the walk animation

scenic burrow
#

How could I instantiate a bunch of prefabs with their own color?

polar acorn
#

What that function is depends on what kind of object it is, if it's a mesh or a sprite or whatever

verbal dome
#

You can see the parameters and transitions in real time

scenic burrow
#

Ok will try thank you!

round pebble
dense root
#

I've got a flash card like-system, and I want to randomly assign the cards. So if the character "あ" pops up, it displays as one of the answers. How do I set it up so that it is random where that card is placed, and the other characters are random characters from an array of strings?

https://gdl.space/latejuzapo.cs

vale olive
#

hello guys, i have this code for a score board and unity is giving me this error, can someone help me pls?

dense root
high walrus
# swift crag You could fix this by writing a while loop

Hey, quick question about this. Can I write the while loop in the update function or should I make a new function for it alltogether? Right now either the enemies aren't moving or I seem to make an infinite while loop each frame that breaks unity Editor alltogether

swift crag
#

Show me what you wrote.

high walrus
swift crag
#

you need to sum up the distance you've traveled

high walrus
#

does this line not work for that?

swift crag
#

no, that just sets distanceMoved to that difference

#

it's not counting anything up

#

also, your loop isn't actually changing which waypoint you're going to

#

you want to move towards your current waypoint, then check how far you went

#

if you didn't move far enough, that means you reached the waypoint, so pick a new waypoint

#

repeat until you move far enough

dense root
#

How do I create an array of buttons?

high walrus
#

if the condition in while is no longer met it stops working right? so wouldn't this if statement I just wrote below the while loop work for that?

swift crag
# high walrus if the condition in while is no longer met it stops working right? so wouldn't t...
float movementRemaining = speed * Time.deltaTime;
Vector3 position = transform.position;

while (movementRemaining > 0)
{
  Vector3 movedPosition = Vector3.MoveTowards(position, points[currentPoint].position, movementRemaining);
  movementRemaining -= Vector3.Distance(movedPosition, movementRemaining);
  position = movedPosition;

  if (movementRemaining > 0)
  {
    currentPoint += 1;
    currentPoint %= points.Length;
  }
}

transform.position = position;

This is what I was thinking of.

rocky canyon
swift crag
#

However, this might bang into some annoying problems with floating point precision. I'm just getting the Vibe(tm)

rocky canyon
#

issue now is that the file doesn't appear until after I leave playmode

vale olive
dense root
#

Where you have the script assigned

rich adder
eternal falconBOT
#

:teacher: Unity Learn ↗

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

vale olive
#

to the score text

dense root
#

Yeah your Score Texto is empty

swift crag
# high walrus if the condition in while is no longer met it stops working right? so wouldn't t...
float movementRemaining = speed * Time.deltaTime;
Vector3 position = transform.position;

while (true)
{
  Vector3 destination = points[currentPoint].position;
  Vector3 movedPosition = Vector3.MoveTowards(position, destination, movementRemaining);

  // we reached the destination!
  if (destination == movedPosition)
  {
    movementRemaining -= Vector3.Distance(position, movedPosition);
    currentPoint += 1;
    currentPoint %= points.Length;
    position = movedPosition;
  }
  else
  {
    position = movedPosition;
    break;
  }
}

transform.position = position;
#

Getting dinner in a min so I need to run

slender bridge
swift crag
high walrus
#

@swift crag I'm dumb and didn't know about Vector3.distance thanks for sharing what you had in mind

swift crag
#

If you do reach the waypoint, subtract the distance you moved and try moving to the next waypoint

dense root
#

Randomize the answer*

high walrus
#

I'm gonna rewrite a bit with the new knowledge and what you shared, will update in a bit how it went. thanks Fen!

vale olive
dense root
vale olive
#

should be, but it is not working! i am desesperate with this

dense root
#

Show your code

vale olive
slender bridge
dense root
# vale olive

Hmm looks correct to my eyes, you're adding a point to the ScoreBoard.Pontucao then re-assigning the text on update

vale olive
#

not a problem, thanks btw

dense root
#

Np

rocky canyon
#

my code outputs .../Assets\SpawnCampGames/Docu...
is outputPath = outputPath.Replace('\\', '/'); normal to use to keep them uniform?
just feels a bit after-thought-ish

#
        string outputPath = Path.Combine(Application.dataPath, filePath);
        outputPath = outputPath.Replace('\\', '/');```
rich adder
#

That's because path builds based on Os

#

It's universal

rocky canyon
#

alrighty..

rich adder
#

Yeah it looks jank but it works lol

rocky canyon
#

was just about to check my save system cs public void Boot() { saveFilePath = Path.Combine(Application.persistentDataPath,saveFileName); _saveData = Load() ?? new SaveData(); } it uses persistent

#

isntead of dataPath

#

was curious if it did the same

rich adder
#

Yeah that's good

rocky canyon
#

i just never debugged it before

rocky canyon
rich adder
#

Yeah is just compatability. Windows is only weirdo with \

#

Both work tho

high walrus
#

Hope I can figure it out on my own next time I run into an issue

swift crag
#

It's a bit of an awkward problem!

#

someone else had a very similar question a few days ago

#

in their case they were overshooting the goal and then getting messed up

remote osprey
#

Hi ppl

#

how ya'll doing tonight

#

I have a few questions regarding OOP and game architecture

#

In general I never saw the reason for using classes and currently, i use them exactly like one would use C structs

#

But recently a friend that's been helping me told me that the way he would do it was making it highly composable using tiny classes, for example, in the card game I'm making what he would do is make each card a different class (it's a hearthstone like)

#

And that sparked a lot of self-doubt in me

#

Like, can I really make this work? Is my coding skills crap?

#

I always much preferred making things as simple as possible, and for me classes seems like an extra fluff that makes things harder to read

#

I really like the functional programming style for this reason, everything is just so simple and easy to read (for me)

rocky canyon
#

sounds like he wants to follow SOLID

remote osprey
#

But, unfortunately, functional is not used as much as OOP in gaming ...

rocky canyon
#

first one being Single Responsibility

remote osprey
#

What is SOLID?

remote osprey
#

should i know that to become a real game dev?

rocky canyon
#

i think so..

#

its a fundamental way of structuring ur code

#

which gets more important.. the more advanced u get

#

i found this video really enlightening when i first heard of the concept ☝️ @remote osprey

remote osprey
#

Thank you for the resources!

#

I'll be sure to take a look at them

rocky canyon
#

thers really no wrong way to code imo.. if ur the only one (or 1 of 2) people working on it.. as long as u stick to a structure you're fine

#

always helps to know fundamental principles like SOLID.. esp when u share ur code w/ others.. go seeking help, or want to integrate someone elses code into urs

remote osprey
#

I see

#

So it's more like a convention

#

Helps to know

rocky canyon
#

sure, u could think of it like that

#

its not a concrete type of solution

#

im 3 years deep in learning c# and unity.. and i still struggle at times about the concepts

#

but keeping them in the back of my mind helps me get going the right direction

#

so i dont end up with spaghetti at the end of the day

#

good luck w/ teh card game tho! i've wanted to do one for a while now.. but it seems too intimidating for me

#

especially when u start thinking about game-flow.. and balancing

remote osprey
#

Hmm so it's okay to do my own spagethi code for now?

eternal needle
# remote osprey But recently a friend that's been helping me told me that the way he would do it...

Well one thing with unity is a lot of the work can be done in editor. Making everything in it's own class instance (assuming we are talking about making 2 card instances from 1 class) might not be too friendly for your artists and non coding peeps. This is where scriptable objects come into play and not everything is declared in code. It exists as assets.
Your tiny classes could be used as separate ways to like attach logic to a card.

rocky canyon
#

lmao.. while u learn? sure

#

i wrote spaghetti for a while.. but the only way to get better at not writing it.. is to know when its happening lol

remote osprey
#

Yeah, I'm not working with anyone else, for now

#

I think that learning about Solid rn would just get in my way, if you know what I mean

#

Cause what's important is that I have my card game working

#

I can learn about solid in a smaller project later on

#

Especially since I'm a beginner at using Unity

rocky canyon
#

i mildly disagree with that

eternal needle
#

Usually it's a lot easier if you can setup some work to happen in inspector. Although the suggestion your friend said kinda has me wondering what your setup is or what they really meant.
Every single new card definitely shouldn't be it's own class

rocky canyon
#

maybe not focus on it.. but i would def read up on it..

remote osprey
#

It's cause, I would have to rework everything if I wanted to apply SOLID in my project

#

Seems kind of a hassle, tbh

rocky canyon
#

noo.. just start from where u are..

remote osprey
#

i almost got everything working

rocky canyon
#

dont go refactor everything for no reason

#

lol

#

care sharing some of ur code?

#

i'd like to see how ur working atm

remote osprey
remote osprey
rocky canyon
#

!code nah, just use an external link

eternal falconBOT
rocky canyon
#

id just like to see what ur Card class looks like

#

like the main meat of the project lol

remote osprey
#

something like this

eternal needle
rocky canyon
eternal needle
#

Its honestly a bad suggestion to even make a unique class for each card.

rocky canyon
#

Oh yes Composition is dope in Unity

remote osprey
#

So, (almost) every card will have it's own method anyway

#

except for cards that do similar effects

#

like summon a 5/5 minion with no effects

#

tbh thats the only case i reuse methods

eternal needle
#

Exactly, but with the suggestion of class for each card, you no longer can reuse methods because you've created a whole class purely for 1 card.

rocky canyon
#

hmm.. soo im betting u have some repeat code

#

or redundant code

eternal needle
#

Composition would mean you just create a method of spawning minions, and attach that logic to a card. Now any card can spawn minions if it has the class to do so

thick nexus
#

Does anybody know how to resize the grid?

rocky canyon
#

many scripts with single responsibilites

#

vs a big monolithic class w/ everything

#

ur script looks good tho..

remote osprey
#

Hmm so maybe I could use something like a WhenCardDraw class?

rocky canyon
#

i like that ur already using switch statements

#

and DoTween ❤️

remote osprey
#

I mean, main problem to me is, i can't do something like DoDamage(x) because my Delegate doesn't accept parameters

#

I didn't find a way to put variable number of parameters through my delegate so i left basically one method for card

remote osprey
#

I tried to do animations without it it was impossible

rocky canyon
#

i add it to every project i start first thing

#

DoTween, TMP, and Cinemachine

remote osprey
rocky canyon
#
public delegate void CardAction(Card card);``` why couldn't u use delegates that have parameters?
#

I would.. I'd use a UIManager

#

just like ur gamemanager..

remote osprey
rocky canyon
#

and call functions on it to update ur text and stuff

thick nexus
remote osprey
#

I don't want to have redundancies in each call

dense root
#

New to dictionaries, how come it is throwing an error that it answerKey does not exist?

eternal needle
remote osprey
eternal needle
remote osprey
#

I honestly don't want to decipher a 10 parameter functoin that I'm using everywhere everytime

dense root
eternal needle
dense root
#

Oh... am I not able to add it there?

eternal needle
rocky canyon
#

@south ruin the only tip i have is to only update ur UI when u need to...
like for example if u updating player health.. dont do it every frame..
instead, when you take damage for example, then you update the UI after you subtract from the health component or w/e

#

w/ a UI manager singleton.. it'd be easy to call a function UpdateHealthBar(newHealthValue);

dense root
#

Ahh thank you so much @eternal needle

eternal needle
remote osprey
rocky canyon
# remote osprey I honestly don't want to decipher a 10 parameter functoin that I'm using everywh...

ever heard of the <Summary> tags?

        /// <summary>
        /// Display text on the screen in real-time for debugging purposes.
        /// </summary>
        /// <param name="text">The text to display.</param>
        /// <param name="position">The position of the text on the screen.</param>
        /// <param name="size">The size of the text.</param>
        /// <param name="textColor">The color of the text.</param>
        public static void RealtimeDebug(string text, Vector2 position, int fontSize, Color textColor, Vector2 widthHeight)
        {``` for example
#

IDE powah 💪

#

at the end of that function u can call w/e functions u need to from the UI_Manager to update the values it initialized

remote osprey
#

Because to me it's still very hard to read when parameters start to stack up too hard

#

like in matplotlib, for example

#

I only remember because of use, but it annoys me and it just doesn't feel good to me

dense root
#

How do I access dictionary values at random?
This is the equivalent of what I am attempting, but with an array

        // Random between two numbers to pick out the random Hiragana
        int randomIndex = Random.Range(0, hiragana.Length);
rocky canyon
# rocky canyon at the end of that function u can call w/e functions u need to from the UI_Manag...

for example, cs public void UpdateVisuals(int health, int stamina) { HealthText.text = $"Health: {health}"; StaminaText.text = $"Stamina: {stamina}"; } would be in ur UIManager script..
and then, in something like ur GameManager:

  private void InitializePlayer()
    {
        player.health = 100;
        player.Stamina = 100;
        UIManager.Instance.UpdateVisuals(playerHealth, playerStamina); //now update the UI
    }```
#
    public void DamagePlayer(int damage)
    {
        player.Health -= damage;
        UIManager.Instance.UpdateVisuals(player.Health, player.Stamina);
    }```
rocky canyon
remote osprey
#

Thnak you very much for your help!

#

I really appreciate it, honestly

rocky canyon
#

what is Cthulu mean?

remote osprey
#

Talking with you guys made me realize that i'm ok

#

I was feeling terrible about my code haha

rocky canyon
#

u didn't come in here.. saying why is this void not working..

#

lol

remote osprey
rocky canyon
#

and u have a singleton GameManager..

remote osprey
#

Yes

rocky canyon
#

i mean everything in ur script is very acceptable

remote osprey
#

Thank goodness haha

#

I mean, there should only be one game manager, right?

rocky canyon
#

its getting a bit chunky..

#

but thats just life lol

rocky canyon
remote osprey
#

My code is chonk

rocky canyon
#

hence why its a singleton

remote osprey
#

Nice single chonk

rocky canyon
#

my gamemanager is Chonk

#

and i've only done the menu screen 😅

digital cave
#

Can you guys tell me which one is a better practice?

Type 1:

using UnityEngine;

public class StateCheckTest : MonoBehaviour
{
    [SerializeField] private GameObject winLoseStateScreen;

    private WinLoseStateCheck _winLoseStateCheck;

    private bool isAlive;

    private GameObject WinLoseStateScreen(WinLoseStateCheck state)
    {
        switch (state)
        {
            case WinLoseStateCheck.Win:
                winLoseStateScreen.transform.GetChild(0).gameObject.SetActive(true);
                Debug.Log("You won");
                break;
            case WinLoseStateCheck.Lose:
                winLoseStateScreen.transform.GetChild(1).gameObject.SetActive(true);
                Debug.Log("You lose");
                break;
        }

        return winLoseStateScreen;
    }
    
    private enum WinLoseStateCheck
    {
        Win,
        Lose
    }
}

Type 2:

using UnityEngine;

public class StateCheckTest : MonoBehaviour
{
    [SerializeField] private GameObject winScreen;
    [SerializeField] private GameObject loseScreen;

    private WinLoseStateCheck _winLoseStateCheck;

    private bool isAlive;

    private GameObject WinLoseStateScreen(WinLoseStateCheck state)
    {
        GameObject activeScreen = null;
        
        switch (state)
        {
            case WinLoseStateCheck.Win:
                winScreen.SetActive(true);
                activeScreen = winScreen;
                Debug.Log("You won");
                break;
            case WinLoseStateCheck.Lose:
                loseScreen.SetActive(false);
                activeScreen = loseScreen;
                Debug.Log("You lose");
                break;
        }

        return activeScreen;
    }
    
    private enum WinLoseStateCheck
    {
        Win,
        Lose
    }
}
rocky canyon
#

dont get urself muted @remote osprey

remote osprey
#

Sorry 😦

rocky canyon
#

no worries.. i accidently muted myself the other day trying to post the Unreal discord link to a troll that was asking why he was even here.. b/c unity scked and unreal was better

rocky canyon
remote osprey
#

Garsh, that's rough

#

Anyway, i should get going

#

i'm already spamming here

#

Thank you for your help!

rocky canyon
#

good luck mate 👍

digital cave
rocky canyon
#

theres a balance game at play..

#

on one extreme u have syntax sugar (pretty short code)

#

and the other extreme is readibility

digital cave
#

So basically If I want people to like me, I should go with Type2

rocky canyon
#

the easier it is to read.. the more collaboration you can expect

#

if its a chore to go thru code.. (even if its nice and tidy) some people wont

digital cave
#

Gotcha, cheers

rocky canyon
#

Type 2 is better imo

swift crag
rocky canyon
#

besides depending on how often u call the WinLoseStateScreen, you have GetChild calls in there.. which ur second one does away with

swift crag
#

It has these enormous brittle lines in the middle

#

winLoseStateScreen.transform.GetChild(0).gameObject.SetActive(true);

rocky canyon
final trellis
#

does Collider.OnCollisionEnter(Collision) work without rigidbodies?

rocky canyon
#

nope

final trellis
#

damn

swift crag
#

This is the worst of both worlds: you wind up with long lines of code that randomly blow up in your face

rocky canyon
#

theres the Character Controller exception

#

a CC will work w/o a rigidbody

summer stump
swift crag
#

I need to go back and more thoroughly test how character controllers interact with the physics system

#

I remember getting some interesting results

#

like a CC entering a non-rigidbody'd trigger collider produces messages...eventually

#

it was inconsistently timed

rocky canyon
final trellis
#

its not for a character collider i was wanting to do collision detection with a custom script thats like rigidbody but only has gravity

rocky canyon
#

or was it navarone?

summer stump
rich adder
dense root
swift crag
lapis pilot
#

Hi i was just testing out the default unity character controller third person scene sample and it works fine on the default character, i swapped out the mesh of the default robot with my own character and it sort of works apart from the fact that when the character jumps it jumps infinitely into the sky, anyone used that defaut asset for testing and knows what that could be?

swift crag
#

Here are all of the places that I use GetChild in my medium-sized game project

rocky canyon
final trellis
#

ig i dont have any reason to skip out on rigidbodies

swift crag
#

One of them is picking a random child of a transform

rocky canyon
#

i found this yesterday.. its pretty useful to gather info @ a glance

swift crag
#

because I just parented all of my spawn points to a single object

#

The other two are explicitly for effects that apply to all children of an object, one at a time

#

That's it. I only use GetChild 3 times in about 26,000 lines of code

#

'cos you almost never need to use it!

rocky canyon
#

🫣 lmao

digital cave
swift crag
#

So prefer a direct reference to MyComponent over storing a GameObject and then using GetComponent<MyComponent>()

#

and prefer direct references to objects over referencing a parent and getting children by index

#

The exception is if the individual children don't really have meaningful differences

swift crag
#

In your case, the hierarchy order is a coincidence

#

If you do genuinely have a situation where you need to use the third child of an object, then yeah, use GetChild -- but that's quite rare

swift crag
#

I used to do this a lot

#
public GameObject myPrefab;

...

GameObject instance = Instantiate(myPrefab);
instance.GetComponent<Florp>().Foo();
#

now I just do this

#
public class MyCoolPrefab : MonoBehaviour {
  public Florp florp;
}

...

[SerializeField] MyCoolPrefab myPrefab;

...

var instance = Instantiate(myPrefab);
instance.florp.Foo();
#

I only have 7 serialized fields that store a GameObject. Most of them are for a cursor system where I am literally just moving an object around

#

...and one shouldn't be serialized, whoops

digital cave
#

Gotcha, thank you for the very detailed explanation again

swift crag
#

no prob (:

swift crag
swift crag
rocky canyon
swift crag
#

it's used to display a single button in a control hint

#

I added the methods when I realized I wanted to put logic into it, instead of having another component just reach in and mess with its public fields

rocky canyon
#
    public void Press()
    {
        sizeGoal = 0.8f;
        returnTimer = 0;
    }

    public void Release()
    {
        sizeGoal = 1f;
        returnTimer = 0;
    }

    public void Raise()
    {
        sizeGoal = 1.25f;
        returnTimer = 0;
    }``` ? whats this Fen ?
swift crag
#

They're used to make the icons react to player input

#

...having this happen on the control list wasn't exactly a design goal

#

but hey, it works

#

Build it once, use it many times (:

#

i should probably hide the splash screen action lol

zenith cypress
#

Build it once, bug, build it twice, new project, port it over, crunch time, forget about it, built it again, forgot you had it Kappa

rich adder
#

thats more like it

swift crag
#

growing stronger each time as I realize the how I blundered last time

#

what sucks is that, when i go back to an older project now, i realize that i've got the old janky system

zenith cypress
#

This reminds me that I need to make a pause ui for my demo. I don't wanna

dense root
#

How do I use the other values of the Random.Range? My intent is to use those values to assign the other Button Text in my Hiragana learning game

// Random button text will be assigned the hiragana[randomIndex]
int randomInt2 = Random.Range(0, 4);
answerButtonText[randomInt2].text = answerKey[hiraganaArray[randomInt]];
swift crag
#

"other values"?

dense root
#

Say you get a random value of 1, how do I get 2-4?

swift crag
#

ah, you want to fill in the other buttons

dense root
#

Correct-a-mundo

swift crag
#

I'd just do a for loop and skip the picked value

#

use continue to skip one iteration

zenith cypress
#

Could loop, use rand as the start index, then wrap i around the length 5Head

swift crag
#
for (int i = 0; i < 4; ++i) {
  if (i == picked)
    continue;

  // do stuff
}
#

Alternatively, don't skip: just do whatever you want to do for the correct answer there

dense root
#

Okay this is where it gets tricky... how do I ensure I'm not using the same value twice?

        for (int i = 0; i < 4; ++i)
        {
            // Set the text randomly between 0 and 4
            answerButtonText[i].text = answerKey[hiraganaArray[Random.Range(0, 4)]];
            // If they're the same
            if (answerButtonText[i].text == answerButtonText[randomInt2].text)
            {

            }
            // If we encounter randomInt2 we just skip it
            if (i == randomInt2)
            {
                continue;
            }
        }
swift crag
#

Pick the random number before the loop

#

Ah, I see what you want

#

You want to shuffle a set of numbers.

#

The simplest way to do this would be to make a list of numbers

#

pick a random index, use that number, and remove it

#

repeat until the list is empty

dense root
#

Whew this is getting tricky haha

swift crag
#
List<int> choices = new() { 0, 1, 2, 3 };
while (choices.Count > 0) {
  int listIndex = Random.Range(0, choices.Count);
  int chosen = choices[listIndex];
  choices.RemoveAt(listIndex);
}
#

bah

#

like so

#

This will give you the numbers 0, 1, 2, and 3, in a random order

gaunt ice
#

The Fisher–Yates shuffle is an algorithm for shuffling a finite sequence. The algorithm takes a list of all the elements of the sequence, and continually determines the next element in the shuffled sequence by randomly drawing an element from the list until no elements remain. The algorithm produces an unbiased permutation: every permutation is ...

swift crag
#

Indeed - Fisher-Yates is great to create an entire shuffled list

#

I use it!

#

I remember having to prove that it worked back in a randomized algorithms class in grad school

ember tangle
#

I have an enum in a class and a function that uses it```public enum Direction
{
Forwards,
Backwards,
Left,
Right
}

public void InvertFormation(Direction direction)
{
}```

In another class calling the function, why does this not work:

formation.InvertFormation(formation.Direction.Backwards); //error

but this does?:

formation.InvertFormation(Formation.Direction.Backwards);

I thought that was only for static member attributes?

rich adder
gaunt ice
#

enum is static member of the class

ember tangle
#

so an enum is automatically static?

gaunt ice
#

const but const is static in c#

ember tangle
#

okay I understand, thanks

polar acorn
ember tangle
#

Hmm this makes less sense to me.

swift crag
#

yes -- nested types are a distinct kind of member

#

If you declare a type inside of another type, you've got yourself a nested type.

ivory bobcat
ember tangle
#

ooooo

#

ok

swift crag
#

The nested type does not belong to a specific instance of the enclosing type, yes

#

just like how static fields don't belong to a specific instance of the type

finite chasm
#

hello. this is a semi-long script so i would understand if it takes awhile to get help. i have asked chatgpt literally over 20 times and every response doesn't work. im wanting to update the text to make the count +1 (1/5, 2/5, etc) everytime i complete a chore for my horror game. however, choresCompleted never updates past the completion of the first chore.

i hope using pastebin is alright here. i dont remember the other sites. https://pastebin.com/Mpjf4Xzr

gaunt ice
#

i dont think a float choresCompleted makes sense unless you will display "total: 1.2345/5 chores completed"
btw i guess choresCompleted should be shared across instances

final trellis
#

quick question just to be sure, does GetComponentInChildren just go straight to the children or does it look through the object its called on first? ik it sounds obvious but you really never know

finite chasm
#

actually thats a stupid question, of course thats what i should do

rich adder
final trellis
#

i knew it

gaunt ice
#

and is this gpt code?

choresCompleted += 1;
 
Debug.Log("Chore Completed!");
Debug.Log("Chore Completed! Total chores completed: " + choresCompleted);
isChoreCompleted = true;<---?
 
choreCompletedCount.text = "Chores Completed: " + choresCompleted + "/5";
 
timer = 0f;
isInteracting = false;
isChoreCompleted = false;<---?
progressBarFill.Value = 0f;
final trellis
#

never trust the way programmers name things

rich adder
#

wish we had a version of it where it can skip the first but oh well

finite chasm
rich adder
finite chasm
#

oh i just saw the two isChoreCompleted's

finite chasm
final trellis
finite chasm
#

im not going to say i didnt use gpt but i dont use it for the whole script, only when i run into issues

rich adder
gaunt ice
finite chasm
#

gpt did tell me however to reset the isChoreCompleted variable after the text is updated.

final trellis
finite chasm
#

hmm ill take a look at it

gaunt ice
#

know what "static" is and what it does

fluid fossil
#

why is OnMouseButtonUp() being called like 9 times?

#
using UnityEditor;
using UnityEngine;

public class Slot : MonoBehaviour
{
    [SerializeField] private bool hoveringOver;
    [SerializeField] public bool slotFull;

    [SerializeField] GameObject itemInSlot;
    GameObject player;

    void Awake()
    {
        player = GameObject.Find("Player");
    }

    void Update()
    {
        if (this.transform.childCount > 0)
        {
            itemInSlot = this.transform.GetChild(0).gameObject;
            slotFull = true;
        }
        else
        {
            slotFull = false;
        }  

        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        RaycastHit hit;

        if (Input.GetMouseButton(0))
        {
            // Debug.Log(Input.mousePosition);

            if (Physics.Raycast (ray, out hit, 100, 1 << 5) && hit.transform.tag == "InvDropArea") //UI Layer only
            {
                Debug.Log(hit.transform.name);

                if (Input.GetMouseButtonUp(0) && slotFull)
                {
                    Debug.Log("trying to drop");

                    itemInSlot.SetActive(true);
                    itemInSlot.transform.parent = null;

                    itemInSlot.transform.position = player.transform.position + new Vector3(Random.Range(-0.5f, 0.5f), 0, Random.Range(-0.5f, 0.5f));

                    itemInSlot.GetComponent<Item>().ResetItemIcon();
                    itemInSlot = null;
                }
            }
            else
            {
                Debug.Log("Not over drop area!");
            } 
        }

        if (Input.GetMouseButtonUp(0))
        {
            Debug.Log("up");
        } 
    }

    void OnMouseOver()
    {
        hoveringOver = true;
    }

    void OnMouseExit()
    {
        hoveringOver = false;
    }
}
rich adder
#

also you should avoid GameObject.Find

fluid fossil
#

in the console it printed "up" 6 times

rich adder
#

are you sure you don't have this script on multipleobjects?

gaunt ice
#

if you have n instances then update runs n times, so print n times

ivory bobcat
fluid fossil
#

it's actually 8 different objects with this script but yeah I do see your point now

#

weird that it only printed 6 times and not 8, but I get why it printed more than once now

latent magnet
#

How can I add an external library to a jslib file?
I want to add the discordsdk javascript library to a jslib for my webgl application, is this possible?

rich adder
latent magnet
rich adder
#

unity webgl build is just embedded inside an html file

latent magnet
rich adder
latent magnet
#

i see

#

i will try that

#

thank you for your time

#

appreciate it

rich adder
latent magnet
#

yea i did read it

rich adder
#

gotcha

latent magnet
#

i just had a problem with embedding the js file

rich adder
#

what is it you're trying to do exactly?

gaunt ice
#

depend on your hardware

rich adder
#

that doesn't explain what you're trying to do and fankly don't feel like asking 20 questions

gaunt ice
#

for vr...

#

you can set the fixed update time in setting btw

#

you can setup a timer and change the fixed dt back to 0.02?

eternal needle
#

is there something you're actually trying to solve with this? Because this arbitrary value would likely fail in a ton of cases. I think it would be better if you introduced a speed multipler, and then your custom fixed DT can be like Time.fixedDeltaTime * multiplier

#

also stuff like rigidbodies wont respect this custom number, so it really does matter what you're using it for

#

50fps constant? theres nothing you can do if the game is only running 50 frames yet i assume you really mean 50 fixed updates per second

#

then dont try to change fixed delta time to compensate. Either interpolate the object (which is a setting for rigidbodies) or write your own interpolation if this isnt a rb

#

a number multiplied by another number. Though i guess it doesnt fully matter if your only use case was fixed delta time. It just really doesnt make sense to use it though, fixed update still runs only 50 times a second. You wont suddenly be running more code

shadow rain
#

so Ive got a script which lets an object follow the mouse but how do i change what axis the mouse rotates around im using ScreenPointToWorld too

hasty sleet
#

It would help if you showed the script

shadow rain
#

alr

#

void Update()
{
Vector3 mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);

    Vector2 direction = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);

    transform.right = direction;
}
eternal falconBOT
shadow rain
#
  void Update()
    {
        Vector3 mousePosition = Input.mousePosition;
        mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);

        Vector2 direction = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);

        transform.right = direction;
    }
tough phoenix
#

sphere mesh not visible?

north kiln
#

Not a code problem, but I imagine that's not the default sphere and it's either too big or small

tough phoenix
#

this is default mesh

#

other meshes appear

hasty sleet
#

transform.right refers to the right-facing Vector3 direction respective to the local transform. I don't think setting this value to another one is meaningful, but I can't verify without my IDE.

hasty sleet
#

Oh God not the quaternions again

#

It's actually not that bad in these docs

astral falcon
#

Can you even set transform.right? Its a fixed value of the transform and you cant magically change the pivot, can you?

hasty sleet
#

I just asked that same Q. Check the docs vertx posted

#

It runs a rotation function

#

In any matter, my intuition is to change transform.right to transform.up

#

If you want to reverse it, just multiply the vector by -1

astral falcon
#

Ahh, my bad. Good to know. I thought always transform directio nvalues are read only 🙂 good call here

hasty sleet
#

I thought that too tbh

scenic burrow
#

Can I set my mesh collider to stick to the shape of my mesh? I wanna be able to go through this ring without it colliding in the center.

#

So it sticks directly to the ring and not covering the middle as well

silk night
#

Just know that physics does not like that, i would split it into 2 half rings

tepid horizon
#

hello im having a problem where my player doesnt orientate towards where my camera is facing. as in like the character parent does but the model as a child of the parent. sorry i dont know what info to give

languid spire
eternal falconBOT
jovial sandal
hardy lintel
#

does anyone know of a way i can make an object disappear when the camera gets close to it? im designing a desert level and id like to have a small oasis that dissapears when the camera pans over towards it

jovial sandal
#

Well something with making a sphere around the player and a if statement when sphere touches object object gets destroyd

languid spire
jovial sandal
#

Or its a fueture

hardy lintel
hexed terrace
hardy lintel
#

and this is in a top down view

hexed terrace
#

or use a shader to dither it out (like Mario Odyssey)

jovial sandal
hardy lintel
hardy lintel
#

so closer you get the more of it fades away

languid spire
hexed terrace
jovial sandal
hardy lintel
jovial sandal
#

Yes it would

languid spire
hexed terrace
hexed terrace
hardy lintel
hexed terrace
#

You don't need to record everything

jovial sandal
hexed terrace
#

You set the alpha value depending on the distance away from the oasis

#

you don't set the value directly to 0

languid spire
jovial sandal
hexed terrace
#

It's Homer Simpson, numbnuts

jovial sandal
#

I know but the meme

hexed terrace
#

¯_(ツ)_/¯

hardy lintel
jovial sandal
#

Bre

#

I cant post gifs

#

:(

hexed terrace
#

and for good reason

jovial sandal
#

Why

#

You yellow smurf

languid spire
#

<@&502884371011731486>

jovial sandal
#

Its just a joke the yellow smurf

#

Pls no ban

#

Mods:)

hexed terrace
languid spire
#

Stop being a troll

hardy lintel
#

i dunno why im so bad at explaining today lmao

hexed terrace
#

Yeah

hardy lintel
#

dang. might just go for the alpha fade then. have it all at once if i have to mess with shaders

jovial sandal
#

Ok i will just say my question i had what are quaternions

hardy lintel
hexed terrace
jovial sandal
#

<@&502884371011731486>

hardy lintel
hexed terrace
#

no need for a collider

hardy lintel
#

how would i make it check to see if its close enough to fade the alpha?

hexed terrace
hardy lintel
hexed terrace
#

No

fickle plume
eternal falconBOT
#

dynoSuccess itsluukgamer has been warned.

hardy lintel
hexed terrace
#

... raycast

#

well, not even that

#

distance between player and oasis transforms

#

google -> unity how to get distance between transforms

hardy lintel
languid spire
hexed terrace
#

google -> unity how to fade the alpha of a material

crude karma
#

when i program i usually just put a bunch of if statements into update. but doesnt that mean that every if statement is being checked none stop? that sounds pretty inefficient computing wise. so is there a way to make it so an if statement is only being checked when needed rather than 24/7, or is that a pointless gesture?

hexed terrace
#

but doesnt that mean that every if statement is being checked none stop?

Yes

that sounds pretty inefficient computing wise.

It is, you don't want every script running Update, you only want it when it's needed

#

You want to learn about events, delegates, etc.. things that listen and are called when needed

crude karma
hexed terrace
#

I do not

#

Maybe look at the new input system, that uses events rather than Update

gaunt ice
#

event is more inefficient than regular function call...
but it easier to maintain and read

crude karma
#

like just having a shit load of if statements in update works just fine for me, but i would like to improve coding wise xD

hexed terrace
timber tide
#

reminder, default input system does just that and polls your input

keen dew
timber tide
#

every single update loop I have some bool to check if I return early or not

crude karma
hexed terrace
#

experience

crude karma
#

dont have a lot of that lol

hexed terrace
#

yet

#

ask yourself - > "does this need to be checked every frame?"

#

size of project doesn't matter

keen dew
#

The rule of thumb is, does this thing inherently need to be checked every frame, or is this something that happens in reaction to something else?

timber tide
#

I say the best comparison to really get an idea is through the default input vs the new input system.

#

Polling vs events

keen dew
#

For example you don't need to check every frame if the player's health is below 0 to show a game over screen, you can check that only when the player's health changes

crude karma
keen dew
#

No it isn't

crude karma
#

@keen dew it isnt? hm, ive just seen some people saying coroutines arent very resource friendly

hexed terrace
#

ok, you took that too literal

"Does this need to be constantly checked? Or does it just need to be checked/ actioned when something else happens/ a button is pressed?"

timber tide
#

Really, the whole discussion is about micro optimizations. There's very little performance difference and to really achieve such a difference between checking some bool every frame.

#

or some minor comparisons. Now, if you were to do some calculations every frame where you would only need to do it once per property access, that's something you can consider.

crude karma
keen dew
hexed terrace
#

The more relevant thing to care about is Clean Code and maintainability.

A long Update method with a bunch of if statements becomes harder to deal with

crude karma
#

true

#

but i find it a little hard to do "clean code" when im the only one looking at it

#

then everything looks clean to me xD

hexed terrace
#

because you're a beginner.. you need to keep doing, learning, reading.

crude karma
#

thats fair

karmic kindle
#

I'm having problems with the Update loop continuously running "HitTarget()" - I've narrowed it down from the other scripts so "Bullet()" is only being called once as it should, but the impact effects duplicate until the "Target" has finally been destroyed.

How would i go about diagnosing this further if you can't spot an obvious mistake?

https://pastebin.com/1NFvP1Eg

crude karma
#

you could do various debug logs between everything to see if they give you the correct results

#

thats usually how i hunt down something that isnt working that i cant find

#

its a bit tedious tho

hexed terrace
#

just add target != null to the if statement (which, for some reason, you set to null twice)

languid spire
crude karma
karmic kindle
#

I was using debug logs to narrow things down to this 😇

languid spire
karmic kindle
#

I started adding more "= null" when I was debugging, once I've found the fix (testing your suggestion now) I'll clear it up again

timber tide
#

I still have a collection of barn animals I use for my debugging which I've a habit of doing from working with some other languages

karmic kindle
crude karma
languid spire
#

although the VS debugger is, afaik, much better than the VS Code one

timber tide
#

stepping through code makes stuff like statemachines rediciously easier to debug

#

but I will still debug log stuff that runs in update loop like constant positional updates

languid spire
karmic kindle
#

With the change - if (dir.magnitude <= distanceThisFrame && target != null)

crude karma
languid spire
#

tbh, imao, at the same time you are learning 'Hello World' you should be learning how to use the debugger. Would save many, many people a great deal of pain

languid spire
karmic kindle
languid spire
karmic kindle
#

I appreciate it but trying to configure VSCode is taking up my brainspace so I can't make use of what you're saying right now. Thank you though.

#

If anyone knows of a better guide than this one, please do share - nothing is matching what I see in VSCode and suggests I need to do some JSON work... 🤷‍♂️

burnt vapor
#

!ide

eternal falconBOT
keen needle
#

Is there a simple way to delete the last char of a string?

burnt vapor
burnt vapor
languid spire
keen needle
#

I love you, ty

shell herald
#

how can i make it so that i can have something trigger at a value and a multiple of a value? eg, (if value 1 = value 2 (and value 2 x2, x3,x4 etc etc))

burnt vapor
#

You want to specify a base value and trigger code when a given value is a multiple of it?

timber tide
#

modulo

burnt vapor
#

Yeah, pretty much use a modulo, I guess?

verbal dome
#

Or division

burnt vapor
#
var baseNumber = 5;
var currentNumber = 8;
var isMultiple = currentNumber % baseNumber == 0;
shell herald
#

aight thx

timber tide
#

modulo cooler than division tho

burnt vapor
#

Not sure how division would work here. Maybe if you check for decimals but that seems unnecessarily complex

zealous hatch
#

hey guys, what would i use to create the same effect as this video in relation to the pointing of the gun and arms. I cant put my finger on how the game does it. Looks almost like the arm, hand and gun are all seperate sprites? I have a look at script that allows the head to point at the curser

timber tide
#

terraria is a good example too

verbal dome
zealous hatch
#

oh really? thank you. I think its just confused me as the look at script works by pivoting around the pivot. I would suppose the pivot for the hand would be the end of the gun and then the pivot for the arm being the joint of the shoulder

burnt vapor
#

If floats were checked then there would also need to be approximation

bleak condor
#

i animated my enemy with 2 8x8 sprites, but when it swithes to the other sprite, it is not aligned at all with the original sprite

zealous hatch
karmic kindle
#

Okay, so I have Debugging configured and I'm looking at the loop in VSCode, I've set the breakpoints and I'm able to step in etc... but what am I actually looking for?

timber tide
#

there's probably more tools around but I've not really toyed with them

karmic kindle
zealous hatch
#

i would assum keep them the same sprite

#

then put pivot point on the handle part

timber tide
#

if you can flip sprites I'd do it as it just saved time

zealous hatch
#

okay ill go give it a try, thank you

timber tide
verbal dome
#

Modulo probably makes more sense for the OP though

karmic kindle
# languid spire look at the names. what you are doing is, in effect. ```cs gameObject = prefab; ...

Is this the right/better way to do it?

I've found out that this is where the bug is - the impactEffect is put as a child object and with any "time" assigned to it, the whole script loops. Any thoughts/advice on why? Essentially this started because I refactored my targeting script, so it has always had a timer in it and worked fine.

    {
        if(impactEffect)
        {
            GameObject effectIns = Instantiate(impactEffect, target.gameObject.transform);//, transform.rotation);
            Debug.Log("Destroy impact effect");
            Destroy(effectIns, 0.5f);
        }
    }```