#๐Ÿ’ปโ”ƒcode-beginner

1 messages ยท Page 103 of 1

rich adder
#

just seems pointless, instead of just assigning it in the inspector and have it ready lol

dusty rivet
#

idk how to explain it but im trying to make an animation for a button where when you hover over it theres a bar that extends just above the word that goes to the right then one that goes down the right side then one across the bottom to the left and one up the right side and i have a ui element thats a bar and it at the top and if i increase the RectTransform.right value the bar will extend along the top but idk how to go abt changing it in code

#

do you know how id go about doing that

unreal imp
#

Or need a cache too?

rich adder
#

looks fine otherwise, although I would approach it completely different

#

my toilet would probably have enum states

dusty rivet
#

or

#

when is it called

rich adder
#

its a quick way to draw UI elements on screen without canvas

#

for testing mainly

dusty rivet
#

like i want to extend it to the right

rich adder
dusty rivet
#

but if i change the scale it extends to the left aswell

rich adder
#

move the pivot to the left side

dusty rivet
rich adder
#

pivot X should be 0

#

Y doesnt make a difference for width

dusty rivet
#

is there i way i can make the right value just go from 350 (which is not extended) to 0 (which is extended)

wintry quarry
dusty rivet
dusty rivet
timber tide
#

yellow

dusty rivet
#

but i want the top bottom and right to be 0

dusty rivet
rich adder
dusty rivet
wintry quarry
#

That's how you set the anchors

ocean blaze
#

Ok I saw this comment a little late and I appreciate the suggestion but what I implemented was that it would basically play even when the seen reset so the same thing as before but this time it mutes/freezes the audio when transitioning to a different scene for example if I am playing and go to the main menu the audio from lvl 1 pauses then when I go back to lvl 1 it resumes same place you left off it that makes sense

#

Do you think this is a good work around or do you see any bugs around the corner I should be aware of?

pliant mist
#

how do I do this?

polar acorn
gentle moat
#

Hi, I am trying to make my player move in the direction they attack, and I was wondering why this might not be working. There is no movement when I attack.
https://gdl.space/yaxobebiva.cpp

twin bolt
#

Does anyone know why this is not loading the "DesiredScene" after the 5 seconds? ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class CrossSceneElevator : MonoBehaviour
{
GameObject PlayerController;
GameObject PlayerCamera;
public string DesiredScene;

AsyncOperation Progress;

private void Start()
{
    PlayerController = GameObject.FindGameObjectWithTag("Player");
    PlayerCamera = GameObject.FindGameObjectWithTag("MainCamera");
}

private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Player"))
    {
        StartCoroutine(Wait());
        Progress = SceneManager.LoadSceneAsync(DesiredScene);
        Progress.allowSceneActivation = false;
        GetComponent<BoxCollider>().enabled = false;
    }
}


IEnumerator Wait()
{
    yield return new WaitForSeconds(5);
    PlayerPrefs.SetFloat("POSX", PlayerController.transform.position.x);
    PlayerPrefs.SetFloat("POSY", PlayerController.transform.position.y);
    PlayerPrefs.SetFloat("POSZ", PlayerController.transform.position.z);

    PlayerPrefs.SetFloat("ROTY", PlayerController.transform.rotation.y);

    PlayerPrefs.SetFloat("CameraROTX", PlayerCamera.transform.rotation.x);
    PlayerPrefs.SetFloat("CameraROTY", PlayerCamera.transform.rotation.y);
    PlayerPrefs.SetFloat("CameraROTZ", PlayerCamera.transform.rotation.z);

    PlayerPrefs.SetInt("Elevator", 1);

    SceneManager.UnloadScene("1.12 Hall");
    Progress.allowSceneActivation = true;
}

}```

polar acorn
twin bolt
polar acorn
#

And what is currently happening

twin bolt
polar acorn
teal viper
#

I'd suggest adding some logs or stepping with the debugger

polar acorn
#

It's probably unloading this object, thereby cancelling the coroutine, before it finishes loading

twin bolt
polar acorn
#

I had assumed you made sure the function was even running first

twin bolt
twin bolt
# polar acorn Never assume

Okay, so it is calling the coroutine, so it must be having issues with the "Wait for seconds" line, or Stopping somewhere.

twin bolt
polar acorn
twin bolt
polar acorn
#

Oh, here's a thought, if you collide again while the operation is going, you get a new async operation and never re-enable allowSceneActivation on the original one

#

You should only run that code if progress is null

polar acorn
slender bridge
#

why not while loop yield return null while the task isnt done and move all your code into the coroutine

IEnumerator Wait()
    {
        var progress = SceneManager.LoadSceneAsync(DesiredScene, LoadSceneMode.Additive);
        
        //other stuff
        
        while (!progress.isDone)
        {
            yield return null;
        }
        
        //other stuff

        SceneManager.UnloadScene("1.12 Hall");
    }

something like that

twin bolt
#

Okay i'll do that now, and i also noticed that the courotine goes through every line of code and stops right before the allowsceneactivation = true.

twin bolt
teal viper
#

Does it work if you load it synchronously?

teal viper
#

Okay, then share your current code

twin bolt
#

With the Scenemanager.Loadscene?

teal viper
#

You can comment that part and keep it for reference. I'm more interested in the latest async loading code

twin bolt
#

Here: ```public class CrossSceneElevator : MonoBehaviour
{
GameObject PlayerController;
GameObject PlayerCamera;
public string DesiredScene;

AsyncOperation Progress;

private void Start()
{
    PlayerController = GameObject.FindGameObjectWithTag("Player");
    PlayerCamera = GameObject.FindGameObjectWithTag("MainCamera");
}

private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Player"))
    {
        //SceneManager.LoadScene(DesiredScene);
        StartCoroutine(Wait());
        Progress = SceneManager.LoadSceneAsync(DesiredScene);
        Progress.allowSceneActivation = false;
        Debug.Log("Done");
        GetComponent<BoxCollider>().enabled = false;
    }
}


IEnumerator Wait()
{
    yield return new WaitForSeconds(5);
    PlayerPrefs.SetFloat("POSX", PlayerController.transform.position.x);
    PlayerPrefs.SetFloat("POSY", PlayerController.transform.position.y);
    PlayerPrefs.SetFloat("POSZ", PlayerController.transform.position.z);
    PlayerPrefs.SetFloat("ROTY", PlayerController.transform.rotation.y);
    PlayerPrefs.SetFloat("CameraROTX", PlayerCamera.transform.rotation.x);
    PlayerPrefs.SetFloat("CameraROTY", PlayerCamera.transform.rotation.y);
    PlayerPrefs.SetFloat("CameraROTZ", PlayerCamera.transform.rotation.z);
    PlayerPrefs.SetInt("Elevator", 1);
    SceneManager.UnloadSceneAsync("1.12 Hall");
    Progress.allowSceneActivation = true;
    Debug.Log("Done again");
}

}```

teal viper
#

Btw, what makes you think you need to call UnloadSceneAsync?

#

Can you comment that out and see what happens?

twin bolt
teal viper
#

LoadSceneAsync unloads any other scene before loading the new one.

#

Unless you load it additively

#

Also, everyone assumed that you don't have any errors in the console, but is that true?

teal viper
#

Okay. The only other thing that bothers me is that you're waiting for 5 sec. What if your scene is not loaded by that time? I think you should use a loop and check the progress too.

twin bolt
# teal viper Okay. The only other thing that bothers me is that you're waiting for 5 sec. Wha...

Like this? IEnumerator Wait() { while(!Progress.isDone) { yield return null; } PlayerPrefs.SetFloat("POSX", PlayerController.transform.position.x); PlayerPrefs.SetFloat("POSY", PlayerController.transform.position.y); PlayerPrefs.SetFloat("POSZ", PlayerController.transform.position.z); PlayerPrefs.SetFloat("ROTY", PlayerController.transform.rotation.y); PlayerPrefs.SetFloat("CameraROTX", PlayerCamera.transform.rotation.x); PlayerPrefs.SetFloat("CameraROTY", PlayerCamera.transform.rotation.y); PlayerPrefs.SetFloat("CameraROTZ", PlayerCamera.transform.rotation.z); PlayerPrefs.SetInt("Elevator", 1); //SceneManager.UnloadSceneAsync("1.12 Hall"); Progress.allowSceneActivation = true; Debug.Log("Done again"); }

teal viper
#

Not if you set allowSceneActivation to false

#
When allowSceneActivation is set to false, Unity stops progress at 0.9, and maintains.isDone at false. When AsyncOperation.allowSceneActivation is set to true, isDone can complete. While isDone is false, the AsyncOperation queue is stalled. For example, if a LoadSceneAsync.allowSceneActivation is set to false, and another AsyncOperation (e.g. SceneManager.UnloadSceneAsync ) initializes, Unity does not call the second operation until the first AsyncOperation.allowSceneActivation is set to true.
#

Please read the docs

#

And look at their example.

teal viper
terse osprey
#

I need help, I am using this script for when my enemy dies. Is kinematic gets switched off but animator isnt getting diables

summer stump
#

Can you show the inspector for the object with Ragdoll?

terse osprey
#

actually I figured it out

twin bolt
# teal viper This would get stuck in "infinite loop" if you do set it to false before.

I might have done what you were mentioning ``` IEnumerator Wait()
{
yield return null;

    Progress = SceneManager.LoadSceneAsync(DesiredScene);
    Progress.allowSceneActivation = false;
    while (!Progress.isDone)
    {
        PlayerPrefs.SetFloat("POSX", PlayerController.transform.position.x);
        PlayerPrefs.SetFloat("POSY", PlayerController.transform.position.y);
        PlayerPrefs.SetFloat("POSZ", PlayerController.transform.position.z);
        PlayerPrefs.SetFloat("ROTY", PlayerController.transform.rotation.y);
        PlayerPrefs.SetFloat("CameraROTX", PlayerCamera.transform.rotation.x);
        PlayerPrefs.SetFloat("CameraROTY", PlayerCamera.transform.rotation.y);
        PlayerPrefs.SetFloat("CameraROTZ", PlayerCamera.transform.rotation.z);
        PlayerPrefs.SetInt("Elevator", 1);
        //SceneManager.UnloadSceneAsync("1.12 Hall");
        Progress.allowSceneActivation = true;
    }
}```
#

Everything is frozen

teal viper
twin bolt
#

How do i unfreeze my unity editor?

summer stump
ivory bobcat
teal viper
#

Could try breaking with the debugger in the loop and manually changing Progress.isDone if it allows you.@twin bolt

terse osprey
#

I need help on one more thing

summer stump
twin bolt
terse osprey
#

This is a code that detects when the enemy is hit and takes damage. on some occasions the weapons fires faster and some of the bullets are ignores like a delay between each registered bullet. How can I fix this so every bullet is registered

ivory bobcat
#

If it's in play mode and you're certain where it's freezing, you could try attaching the ide to the running process with a break point at the looping location in code.

summer stump
terse osprey
#

the bullets are projectiles spawned when I fire and TakeDamage is a public void

summer stump
terse osprey
#

IsHit and routineStarted are set true for the projectile scripts and they are moved using transform

summer stump
#

If you want to use the transform, raycast ahead of it to check the space in between the teleportation points

#

Or just use a rigidbody and set interpolation on and collision detection to continuous

#

I think the delay between the registered hits is caused by the routineStarted bool, that's why I was asking about it

terse osprey
#

Should the bool be removed entirely

#

because I was reusing another script but I think this one doesnt need the routine started bool

summer stump
# terse osprey Should the bool be removed entirely

Well, I still have no idea what routineStarted represents, so I have no idea.
Are you starting a coroutine that causes bullets to not cause damage for some amount of time, because that's all I could guess

terse osprey
#

I think I understand what is happening here and ill figure the rest of it out

#

Thanks for the help

rich adder
twin bolt
summer stump
ruby ember
#

can someone send me a code of mobile player controller mobile (like player movement joystick and rotation)

summer stump
ruby ember
#

okay

twin bolt
abstract finch
#

Is there a way to make a float Round itself to 1 or -1 from a float if its above 0 using one of the mathf functions?

summer stump
polar acorn
abstract finch
twin bolt
abstract finch
summer stump
ruby ember
#

Well

#

I need this script because I need to test something

twin bolt
summer stump
# ruby ember It means is a yes?

It means an absolute no. If you want to gamble on the extremely unlikely case someone will just give you code, you can.

Or you can show what you have done and explain why it didn't work, and we can help you with ig

summer stump
ruby ember
#

Oh well I did this
Joystick works but I need to add the player movement and rotation

teal viper
edgy hearth
#

hey so im coding a wall running script, but if i look slightly towards the wall instead of straight forward i slow down. does anyone know of a way so i can make it that you can look within a few degrees and the player wont slow down?

dawn rampart
#

when i flip the character it flips to far because of the sprites

#

is there any way to fix this?

rich adder
dawn rampart
#

flip the gameobject by rotating its x by 180

rich adder
#

you rotate on y 180 to flip in 2d

quick ruin
#

how do I make this a System.Func<bool>

dawn rampart
dawn rampart
rich adder
#

youpassed a bool

quick ruin
#

how would I change a bool into a func<bool>

rich adder
#

you could prob make it anonym func. WaitUntil(()=> Condition == something)

quick ruin
#

=> worked, thanks ๐Ÿ™‚

woven crater
#

im thinking of create a arbitrary time counter by using time.delta time to increase a float variable and use that variable to do other time based task
are\ there any better method?

rich adder
#

is fine for most cases

#

there is also coroutine waitUntil

rich bluff
#

if its global make sure it updates before everything else

charred spoke
#

Isnt this Time.time with extra steps?

woven crater
#

thought it only count up and cant be reset

charred spoke
#

It cant but why do you need it to reset? Usually you just calc a div in time so you if(currentTime-prevTime > someNum) doThing() prevTime = currentTime

woven crater
#

Oh neat

woven crater
charred spoke
#

If you keep track of prevTime in each gameObject then I dont see how itโ€™s gonna be synced

rich bluff
#
class MyScript{
  float startTime;
  void Start() {
     startTime = Time.time;
  }

  void Update()
  {
      print($"Internal time {Time.time - startTime}");
  }
}
charred spoke
#

What exactly are you trying to do I might have a git repo for you

woven crater
#

Hmmm I see. I just assume how it work while going to school. Will figure it out for my own

violet topaz
#
public class Attacking : MonoBehaviour
{
    public int attackDamage;
    public float attackDistance;
    public float attackDelay = 0.4f;
    public float attackSpeed = 1f;

    public type state;
    public enum type
    {
        fists,
        weapon
    }
    private void Start()
    {
        state = type.fists;
    }
    private void Update()
    {
        Weapon();
    }
    private void Weapon()
    {
        if (state == type.fists)
        {
            attackDamage = 1;
            attackDistance = 2;
            attackSpeed = 1f;
            attackDelay = 0.4f;
        }

        if (state == type.weapon)
        {
            attackDamage = 2;
            attackDistance = 3;
            attackSpeed = 1.5f;
            attackDelay = 0.4f;
        }
    }
}

Instead of the attack damage or any of them being set to 1 and only being able to be changed in the code how would I change it in the inspector

eternal needle
#

you dont need to run it every frame, only when the state is updated

violet topaz
#

so how would i fix it

eternal needle
static cedar
weak talon
#

im using instantiate to spawn my bullet
why when it spawns in the hiearchy it is set to inactive please help. Also it was working like 5 seconds ago.

eternal needle
undone inlet
#

My game screen is made with UGUI, and I'm using Post Processing's Bloom effect, and I realized that it will work on all the Images in my screen, and I only want one of them to glow, and the others don't, how can I do it?

eternal needle
eternal needle
weak talon
#

sorry for crossposting just please help me

topaz mortar
#

Is this too much?
Dictionary<int, List<Dictionary<string, object>>> returnDic = new Dictionary<int, List<Dictionary<string, object>>>();
The outer Dictionary would hold monster id's
The list is then a list of the combat logs each with it's own inner dictionary of log values

#

Or is that perfectly standard in C#?

ivory bobcat
#

Is there a reason you're using a dictionary instead of a list for the outer collection?

gaunt ice
#

why the value cant be a custom class ie Dictionary<int,List<LogClass>>
dictioanary<string,object> sounds like json format

weak talon
#

im using instantiate to spawn my bullet
why when it spawns in the hiearchy it is set to inactive please help. It was working and i dont know what i did

ivory bobcat
#

Is the prefab active?

gaunt ice
#

since the object is inactive

weak talon
topaz mortar
gaunt ice
#

check if something that set it to be inactive, especially the code after Instantiate

queen adder
#

i have a question if i make a game with unity and share it with friends and play it multiplayer will it cost anything

ivory bobcat
weak talon
weak talon
ivory bobcat
#

Are there any components on it that's setting it inactive?

#

Is the spawner/manager setting it inactive?

topaz mortar
weak talon
queen adder
ivory bobcat
#

Surely one of the above suggestions isn't what you think it is.

topaz mortar
queen adder
topaz mortar
topaz mortar
weak talon
#

what can make it set to inactive

topaz mortar
#

did you ctrl z a reference that you need to set in the editor?

queen adder
weak talon
#

no i checked the player prefab and everything is set to the right thing. like when i click it works perfectly but the bullet is just set to inactive

topaz mortar
#

also completely not related to coding

queen adder
topaz mortar
#

it took me 15 seconds to find

queen adder
weak talon
#

im gonna deelte all the shoot code and write it again

topaz mortar
#

also if you open your prefab (double click it so it's open in your scene)
then in the inspector on the right, is it active?

weak talon
#
        if (Input.GetMouseButton(0) && canShoot)
        {
            Instantiate(bulletPrefab, firePoint.transform.position, firePointOrientation.transform.rotation);

            StartCoroutine(ShootCooldown());
        }

yes it is set to active

topaz mortar
weak talon
topaz mortar
#

show a screenshot of your full unity screen with the prefab open

weak talon
eternal needle
topaz mortar
short perch
#

After a month of using c#, I can finally fix compiler errors sort of easily

topaz mortar
weak talon
#

no

topaz mortar
#

are bullet1 & 2 active?

weak talon
#

yeah

topaz mortar
#

what if you drag the prefab in your scene? is it active?

weak talon
#

yeah

topaz mortar
#

then you have code somewhere setting it to inactive ๐Ÿ˜›

weak talon
#

because im 100% sure i do not have any setactive codes anywhere

topaz mortar
#

ctrl f your project for SetActive(false)

weak talon
eternal needle
weak talon
#

how. I put gameObject.setactive(true) in void UPDATE in the bullet script and it still is set to inactive

topaz mortar
topaz mortar
weak talon
topaz mortar
#

try deactivating the network component and see if your bullet works

eternal needle
topaz mortar
#

but like bawsi is saying, multiplayer is hard ๐Ÿ™‚

weak talon
#

nothing really works when i disable it

topaz mortar
weak talon
topaz mortar
#

well you did something ๐Ÿ™‚ but I've never worked with network components so can't help with that

#

but it makes a lot of sense that if you miss-configure the network component the bullet wouldn't appear on the client/server

eternal needle
weak talon
#

thats the only errors

topaz mortar
#

while you have an error in your code unity can't re-compile the code
so as long as you don't fix that error, your code won't update

weak talon
#

thats only there when i click play because the camera is being set to a parent of the player and it isnt instantly doing it because it only shows up the camera when i click client and server

topaz mortar
#

try a debug.log when you spawn the bullet and then another one for the active state

#

then keep adding debug.logs until you figure out what's happening
at least that's how I fix my bugs

weak talon
#

hoow can i make a debug.log for the active state?

topaz mortar
#

Debug.Log(gameObject.activeSelf)

weak talon
#

should it debug the state its in

#

like if it is active or not

#

ok so i just found this out. When the game is started and i drag in the bullet prefab it is set to inactive

#

nvm that is for everything i put in

#

if i put the bullet prefab in the scene then click play. it automatically sets it to inactive

topaz mortar
#

it's most likely just not set up properly for the network
it might only be displaying on the server or only on the client
or it might not be set up so it defaults to not display
time to go watch some tutorials on networking ๐Ÿ˜‰

weak talon
topaz mortar
#

maybe you removed a piece of code that makes it active in the network
or maybe you clicked something in the network component
or maybe something in your client/server setup changed
or maybe none of that
it's impossible for anyone to tell

#

if it was working before, just re-do what you did earlier

weak talon
#

i did. i ctrl z all the way to the very start of my session

eternal needle
#

this would've been like a 2 second issue. you look at the code in a previous commit, see the changes, done

sour arch
#

Not the right channel im sure but i cant find a 2d channel lol
Player goes behind trees in the main menu, yet in the game they're in front? Any idea why this would be? Tried trouble shooting by changing tags around and im stuck, is it a script problem or anything else?

topaz mortar
#

any recommendations for version control with Unity?

#

I'm currently just pushing all my files to github, but haven't really needed to use it so far

sour arch
#

I use github for my projects personally

#

apparently the unity built in one is quite good too, used collaborate in the past and never had issues

eternal needle
# topaz mortar any recommendations for version control with Unity?

github as you are using, pretty much always. Git is used in every other CS field so its very useful to be able to transfer this knowledge elsewhere.
Just commit every often you make changes, I havent needed to go back to previous commits yet but at least i can if i want to

topaz mortar
weak talon
#

is there any other way i can go back to another commit without github or anything?

eternal needle
#

there is no commit if you arent using version control

topaz mortar
#

I've heard git is terrible for unity

#

but at least it should work for the scripts

eternal needle
sour arch
weak talon
#

nvm found it

weak talon
topaz mortar
sour arch
#

From my memory yes

topaz mortar
#

I'm terrified of having something go wrong in my project and having to restore a commit LOL

sour arch
#

Its been a while since i worked on a big 3d project lol

eternal needle
# topaz mortar I've heard git is terrible for unity

The only issue is you cant upload very large files, but those can be shared by any other means.
I think the other solutions are garbage, the skillset arent transferrable to any other fields of work. Their "benefit" is that they are integrated with your IDE, but it is useless. There is premade GUI's like github desktop, where everything is just done in one click

topaz mortar
#

also still need to set up dev environment and database & stuff -_-

#

meanwhile ppl are playing my game lol

sour arch
#

I worked on a spaghetti code game with like hundreds of ui elements and it saved it all fine but that was a few years ago

#

i doubt it would have changed tho

worldly jolt
#

my collider isnt working idk why can someone help

topaz mortar
#

do you think you have provided enough information for anyone to help you?

worldly jolt
#

no

#

sorry im working on it

#

my code is messy this is first bit

eternal needle
worldly jolt
eternal needle
worldly jolt
#

that is code which just places down something and i can buy it and whatever it just for tower defense

worldly jolt
#

anyways it should change to a red colour or be not placeable but it still is placed down

eternal needle
worldly jolt
#

also that commented out bit at the bottom wasnt meant to be commented out

#

alr

weak talon
#

a solution is just helping me

#

and not judging me presumabally not understanding that

#

this chat is for people asking questions and if i ask a question and you judge me you are not very good and should just not respond

eternal needle
topaz mortar
#

bawsi has not been negatie at all, in fact they have given good advice

#

did you bother looking up what a stack trace is or how to debug it?

#

we're not here to make your game for you, we're here to offer tips and advice, but you still have to do the work yourself

weak talon
eternal needle
#

You really cannot ask "how can i use that to find out what is doing it" and expect people know what you want

#

what is "that" and "it"?

topaz mortar
#

you come here to ask things after you've spend an hour trying to figure them out yourself
not because you're too lazy to google something

weak talon
#

and me and you have been talking for a while because we cant figure it out

topaz mortar
#

well the reason we can't figure it out is because you're trying to do something that is very hard and seem to lack basic knowledge of both unity and programming

brave tapir
#

hi chatgpt isnt giving me any answers that work, this is my code for flipping a sprite on its x axis based on rotation but its not working properly, sometimes it flips properly but especially when its moving down to the left it doesnt flip:

public static void Wandering(ref Vector2 targetPoint,  Vector2 centerPoint, float wanderRange, float speed, ref float direction, GameObject subject, SpriteRenderer spriteRenderer)
{
     subject.transform.position = Vector2.MoveTowards(subject.transform.position, targetPosition,   moveSpeed * Time.deltaTime);

      
      Vector2 tempDir = targetPoint - (Vector2)subject.transform.position;
      direction = Mathf.Atan2(tempDir.y, tempDir.x) * Mathf.Rad2Deg;
      
      // Flip the character based on movement direction
      if (tempDir.x < 0)
      {
          // If moving left, flip the character to face left
          spriteRenderer.flipX = false;
      }
      else if (tempDir.x > 0)
      {
          // If moving right, keep the character facing right
          spriteRenderer.flipX = true;
      }
      if ((Vector2)subject.transform.position == targetPoint)
      {
          Debug.Log("new point");
          targetPoint = RandomPoint(centerPoint, wanderRange);
      }
}

topaz mortar
#

so getting a c# basics lesson is solid advice

worldly jolt
#

https://gdl.space/odedamizuz.cpp here is my code currently this just is for a tower defense placement system it took about 45 minutes to get up to this point with a few other features also. It should change colour when it is touching a collider and not be placeable however no matter what it is still placeable and does not change colour and you can see in the console it is logging whether it is placeable every 0.5 seconds, also how much wood and stone you have but just ignore that. Ill show you a video of what happens and it is not what should happen based on the code.

#

there is that how i should have done it following the readme

eternal needle
topaz mortar
topaz mortar
eternal needle
worldly jolt
#

noone gonna help me i did what u told me to

brave tapir
eternal needle
topaz mortar
#

even if you're right

eternal needle
#

if (placeable); being one of those if statements

topaz mortar
eternal falconBOT
brave tapir
worldly jolt
weak talon
topaz mortar
#

drop it

worldly jolt
weak talon
eternal needle
worldly jolt
#

no it doesnt work

#

i didnt have them before

worldly jolt
#

i was just gonna test something

#

anyone got any ideas whats wrong

#

if u need more info just ask

#

https://gdl.space/uhitarezad.cpp here is my code currently this just is for a tower defense placement system it took about 45 minutes to get up to this point with a few other features also. It should change colour when it is touching a collider and not be placeable however no matter what it is still placeable and does not change colour and you can see in the console it is logging whether it is placeable every 0.5 seconds, also how much wood and stone you have but just ignore that. Ill show you a video of what happens and it is not what should happen based on the code.

eternal needle
#

the values should be between 0 to 1

worldly jolt
#

they were red before

#

ill show you a test

eternal needle
#

make the colors public or [SerializeField] and just see in the inspector what they are

worldly jolt
#

im just making a test where i can manually change between the colors i have selected

#

give me a sec

#

ok i commented out the old colour changer and added a function to update which allows me to edit the color in runtime

frozen hamlet
#

I recommend handling the mouse input in your update function

worldly jolt
#

this is edited i couldnt be bothered using the website

worldly jolt
#

ill post vid of what happens with new script

frozen hamlet
#

I am not sure I have never touched OnMouseDown event but I recommend using Input.GetMouseDown

eternal needle
# worldly jolt

i dont really get what this new method is for, where has this color variable come from and where is it being set? Still, you should do what i suggested above and see what the color actually are instead of assuming what the colors are

worldly jolt
#

@eternal needle the colors are right

#

it goes red

#

when i change it

eternal needle
#

oh you are doing that in inspector

worldly jolt
#

yea

#

just to change to the presets manually

#

color is a public string also

frozen hamlet
#

Wait new SpriteRenderer... is that something you can so in C# above the awake function...?

worldly jolt
#

yea i couldnt get the normal one to do anything for some reason

#

its just a reference

north kiln
worldly jolt
#

im not creating a new one

#

but you can do that in awake

frozen hamlet
eternal needle
north kiln
#

There's a difference between redefining variables and creating new instances, they're redeclaring

worldly jolt
#

both objects im testing on have box colliders so it should be triggering

north kiln
#

There's a resource pinned to this channel for debugging physics messages

worldly jolt
#

no object had a rigidbody im just gonna test now if it works

worldly jolt
#

oop still not working

#

yup it still isnt owrking

#

i found the issue i am using transform.position which bypasses the physics still thanks vertx

#

ill test tommorow cause i have to go now hopefully i remember.

brave tapir
# eternal needle does it not flip at all when going down left? I would debug what tempDir is, may...

here is the full code, they definitely move to the correct point they just dont always face the right direction

public static void Wandering(ref Vector2 targetPoint,  Vector2 centerPoint, float wanderRange, float speed, ref float direction, GameObject subject, SpriteRenderer spriteRenderer)
{
     subject.transform.position = Vector2.MoveTowards(subject.transform.position, targetPosition,   moveSpeed * Time.deltaTime);

      
      Vector2 tempDir = targetPoint - (Vector2)subject.transform.position;
      direction = Mathf.Atan2(tempDir.y, tempDir.x) * Mathf.Rad2Deg;
      
      // Flip the character based on movement direction
      if (tempDir.x < 0)
      {
          // If moving left, flip the character to face left
          spriteRenderer.flipX = false;
      }
      else if (tempDir.x > 0)
      {
          // If moving right, keep the character facing right
          spriteRenderer.flipX = true;
      }
      if ((Vector2)subject.transform.position == targetPoint)
      {
          Debug.Log("new point");
          targetPoint = RandomPoint(centerPoint, wanderRange);
      }
}```
topaz mortar
#

how is this function triggered?

brave tapir
#

its in the Update() of an object but this function is the Az class and is called as Az.Wandering(arguments);

#

Az is my shortcuts class for custom functions that i will be reusing in this and future projects

topaz mortar
#

so you call this function on every Update()?

keen dew
#

it's moving towards targetPosition but rotating towards targetPoint

brave tapir
#

i do yes

brave tapir
# keen dew it's moving towards targetPosition but rotating towards targetPoint

sorry I copy pasted the code of the function

    public static void MoveTowardsPoint( GameObject subject, Vector2 targetPosition, float moveSpeed)
    {
        subject.transform.position = Vector2.MoveTowards(subject.transform.position, targetPosition, moveSpeed * Time.deltaTime);

    }

so that its exposed to you, the targetPosition should be named targetPoint

keen dew
#

can you share the exact code you have, without editing it

brave tapir
#

sure thing:

public static void Wandering(ref Vector2 targetPoint,  Vector2 centerPoint, float wanderRange, float speed, ref float direction, GameObject subject, SpriteRenderer spriteRenderer)
{
    

    MoveTowardsPoint(subject, targetPoint, speed);
    Vector2 tempDir = targetPoint - (Vector2)subject.transform.position;
    direction = Mathf.Atan2(tempDir.y, tempDir.x) * Mathf.Rad2Deg;

    // Flip the character based on movement direction
    if (tempDir.x < 0)
    {
        // If moving left, flip the character to face left
        spriteRenderer.flipX = false;
    }
    else if (tempDir.x > 0)
    {
        // If moving right, keep the character facing right
        spriteRenderer.flipX = false;
    }

    if ((Vector2)subject.transform.position == targetPoint)
    {
        Debug.Log("new point");
        targetPoint = RandomPoint(centerPoint, wanderRange);
    }
}

public static void MoveTowardsPoint( GameObject subject, Vector2 targetPosition, float moveSpeed)
{
    subject.transform.position = Vector2.MoveTowards(subject.transform.position, targetPosition, moveSpeed * Time.deltaTime);

}

public static Vector2 RandomPoint(Vector2 centerPosition,float range  )
{
    // Calculate a random direction within the move radius
    var randomDirection = Random.insideUnitCircle.normalized * range;

    // Calculate the new target position within the move radius around the center
    return centerPosition + randomDirection;
}
keen dew
#

The only thing that I can see is that the direction should be determined before moving the character but that shouldn't matter until the frame when it reaches the target

topaz mortar
keen dew
#
    // Flip the character based on movement direction
    if (tempDir.x < 0)
    {
        // If moving left, flip the character to face left
        spriteRenderer.flipX = false;
    }
    else if (tempDir.x > 0)
    {
        // If moving right, keep the character facing right
        spriteRenderer.flipX = false;
    }

both branches set flipX to false

brave tapir
#

yeah thats a typo i already fixed

keen dew
#

but it's correct in the earlier snippet so ๐Ÿคท

brave tapir
#

sorry i did an undo one too many times before posting

#

the second time

topaz mortar
keen dew
#

I assume it's the guy on the left who's walking backwards at the start

brave tapir
brave tapir
#

i mean i only came here because chatgpt cant figure out the issue and i keep looking at the code and being like, i dont see anything wrong

topaz mortar
#

add some debug.logs to see if tempdir is the expected value

brave tapir
#

ok

topaz mortar
#

not sure if it's relevant
but you have a case for x < 0 and another for x > 0 - can x ever be 0? that is not handled

keen dew
#

That's normal. If the character doesn't move horizontally then it doesn't need to flip left or right

brave tapir
sour arch
#

How can i create free space text?

#

I wanna add a little something here but i can't find out how, tried a google but came up empty for what im aiming fro

fierce shuttle
brave tapir
sour arch
#

Damn it my unity crashed

errant pilot
#

Guys can someone explain the logic here before i break my pc

keen dew
#

The console rounds the values

errant pilot
#

ohh actually ok thank you

ivory bobcat
#

Maybe you should tell us what's wrong

#

If you're referring to the equality check with the last debug, it's likely due to floating point precision error. Use Unity Math f Approximately

keen dew
#

Vectors already use that for comparison

ivory bobcat
#

Ah, my mind slipped.

#

Thought we were working with single values for some reason notlikethis

topaz mortar
spiral oak
#

Should I use Git instead of GitHub desktop for version control?

brave tapir
#

Lol

#

Thank u for everyones help ๐ŸŒธ

severe drum
#

im trying to make a cemra manager for a turn based game, im trying to make the camera to move a little bit in the direction of the unit that is starting a action, i have a center camera position for the group and the unit position.
i want to move the camera a little bit in the direction of unit but not center on the unit. how can i make a point of position btwn he group camera position and the unit position?

eager elm
severe drum
#

and thx

#

๐Ÿ™‚

hexed fable
#

may i ask you something guys

prime lodge
#

does anybody has some idea how to fix this?

slender nymph
#

the two parameter overload of Instantiate expects an object and a transform to set as the parent. if you want to specify a position then you need to provide a rotation too

hexed fable
#

im new here so i just wanted to know if its okay to ask questions in this channel-

queen adder
#

is it better to write your own script that will aauto adjust a rectransform's width based on a text on its child (checks every Update()) or just keep using layout groups for it?

frosty hound
hexed fable
#

oh

slender nymph
#

did you click the link i sent?

queen adder
#

it's a consistent check so, if I can do it better one way, imma go there

prime lodge
hexed fable
#

im new at unity, i did a movement but i wonder something, lot of unity tutorial videos has that meshed ground, how can i do that? because its too hard to distinguish around without meshes

slender nymph
# prime lodge yes

then surely you saw the overload that accepts a prefab, Vector3, and Quaternion as well as the example code that uses that overload

slender nymph
hexed fable
#

i cant find anywere, is there any way to do this?

slender nymph
#

again, not a code question. and to do that you just use a material with that texture

hexed fable
#

okay now here goes a code question

#

hold on-

#

this happens when i try to change material

#

it scales the image

slender nymph
#

still not a code question

hexed fable
#

how-

slender nymph
#

if you think it is a code question, then share your code

hexed fable
#

ur right, where can i ask this thing?

slender nymph
hexed fable
#

oh thanks

slender nymph
#

what part of that are you not understanding?

sour arch
#

in the link he provided it gives examples

prime lodge
#

iam not a native speaker of english

slender nymph
#

a method overload is a method that has the same name but different parameters. notice how in the link i sent there are 5 Instantiate methods immediately visible. those are the overloads for Instantiate

bold nova
#

Im trying to stop all spawning coroutines in spawner script, if session ended, someshow even when game does end and bool in script manager set to false, nothing happens in spawn script

    private void Update()
    {
        if(!sessionManager.gameIsOn)
        {
            StopAllCoroutines();
            Debug.Log("All coroutines stopped");
        }
    }
dusty rivet
#

how do i change the color of an image in code using the leantween library

slender nymph
bold nova
#

no, no. I meant when player dies. Nothing to do with exiting application

slender nymph
#

then you need to provide more context about what is actually happening at the time you expect this code to run. because i don't know if this is attached to an object that is being destroyed, whether it's a completely separate object that persists, etc

merry spade
#
    void Update()
    {
        dirX = Input.GetAxis("Horizontal");
        dirY = Input.GetAxis("Vertical");


    }
}

How can I turn those two variables into a direction vector to apply velocity into the direction the controller stick is facing?

slender nymph
#

Do you know how to create a Vector2 or Vector3?

bold nova
#

sure. There's a spawn object with a spawnScript attached, that is active all the time. SessionManager is also just an empty gameObject with session manager script. When game session starts i set bool value gameIsOn in the sessionManager to true and startInvoleRepeating to spawn spikes from it. In spawnScript in update method as long as gameIsOn == true (read from session manager script), it should allow all InvokeRepeating methods. But when player collides with a spike or an arrow EndSession in sessionManager is called, there i change the gameIsOn to false and it cancels all invoke methods. Ill send all relevant code in a sec

slender nymph
#

InvokeRepeating methods are not coroutines

#

you use CancelInvoke to stop those

bold nova
#
public void StartSession()
{
........

    gameIsOn = true;
}


 private void Update()
 {
     if(!sessionManager.gameIsOn)
     {
         CancelInvoke("SpawnSpikes");
         CancelInvoke("SpawnBoost");
         Debug.Log("All coroutines stopped");
     }
 }
bold nova
#
  public void EndSession()
  {
      //stop spawner from spawning anything
      gameIsOn = false;

      enemy.StopShooting();

      enemy.enemyAnim.SetBool("EndOfGame", true);
      spawner.gameObject.SetActive(false);

      loseMenu.SetActive(true);
      endScore.text = "Score:" + score;
  }
#

update above is in the spawnScript

slender nymph
#

please share all of the relevant !code using a bin site. these random disjointed snippets are not providing enough context to know when/where things are actually happening

eternal falconBOT
eager elm
split dragon
#

Hi. I wanted to build my project, but an error pops up (there are 8 errors in total, but they are all related to the class: Editor. To be honest, I took this script from another person from YouTube, and I don't know what this Editor does or how it can be fixed.

languid spire
languid spire
split dragon
languid spire
#

Do you see one?

split dragon
languid spire
sour arch
#

Anyone able to point me in the right direction for something?

Trying to have multiple doors leading to different rooms and i was wondering how i do it, just pointing me in the right direction would help immensely. I know how to handle scene changes normally (main menu -> scene / Scene 1-> scene2 (If there is only 1 door)) but multiple is stressing me out lol

split dragon
prime lodge
#

does anybondy know why this doesnt work?

slender nymph
#

what are you expecting that to do and what is it doing instead?

#

or is this just your attempt at resolving the issue you asked about earlier?

prime lodge
sour arch
#

well what're u hoping for?

prime lodge
slender nymph
#

let me guess, you're destroying this object and expecting that newly instantiated one to persist?

prime lodge
#

kinda

slender nymph
#

that's why it doesn't work. child objects are destroyed along with their parent objects. and since you are using the overload that specifies a parent you are making the instantiated deathEffect a child of the object you are destroying

#

just pass a position and rotation instead of a transform

prime lodge
#

isnt it the same?

slender nymph
#

no for exactly the reason i just described

prime lodge
#

but how should i do it

#

with variable?

prime lodge
#

ok i will try it

#

it works๐Ÿ˜ญ

#

god thanks

#

you helped me so many times

half lynx
#

In Unity Netcode, I am able to set the NetworkVariable HostID when I am the host. However, it seems that I cannot set the NetworkVariable ClientID when I am the client. Essentially, I want to set a string (ClientID) for the host from the client side. Can someone provide guidance or help me with this?

slender nymph
deep bear
#

Hey all, I'm trying to figure out what I'm doing wrong when trying to load a JSON file into a struct.

In JsonLoader.cs:

{
    public static TextAsset creatureJsonFile;

    [RuntimeInitializeOnLoadMethod]
    static void ReadJSONFiles()
    {
        Debug.Log("Reading JSON Files ...");

        try
        {
            StreamReader sr = new StreamReader("Assets/JSON/creatures.json");
            Debug.Log("Read creature file done");

            creatureJsonFile = new TextAsset(sr.ReadToEnd());
            CreatureDataList creatureList = JsonUtility.FromJson<CreatureDataList>(creatureJsonFile.text);
        }
        catch (Exception e)
        {
            Debug.Log("Couldn't read creature file");
            Debug.LogError(e);
        }
    }
}```

`CreatureData.cs`:
```[System.Serializable]
public struct CreatureData
{
    public string id;
    public string creature_name;
    public string primary_type;
    public string secondary_type;
    public string tertiary_type;
    public int max_health;
    public int attack;
    public int defense;
    public int speed;
    public string sprite_path;
}

[System.Serializable]
public struct CreatureDataList
{
    public CreatureData[] creatures;
}```

`creatures.json`:
```{
    "creatures" :
    [
        {
            "id" : "0011"
            "creature_name" : "Sheel",
            "primary_type" : "Water",
            "secondary_type" : "",
            "tertiary_type" : "",
            "max_health" : 70,
            "attack" : 10,
            "defense" : 7,
            "speed" : 10,
            "sprite_path" : "res://Assets/Sprites/Creatures/village/sheel.png"
        },
        {
            "id" : "0021"
            "creature_name" : "Flatchling",
            "primary_type" : "Fire",
            "secondary_type" : "",
            "tertiary_type" : "",
            "max_health" : 80,
            "attack" : 9,
            "defense" : 9,
            "speed" : 3,
            "sprite_path" : "res://Assets/Sprites/Creatures/village/flatchling.png"
        },
    ]
}
#

What am I doing wrong?

slender nymph
#

well for starters i hope this is just for editor tooling considering none of those paths will exist in a build

dusty rivet
#

does anyone know what this error means? ```Unable to use UDP port 56638 for VS/Unity messaging. You should check if another process is already bound to this port or if your firewall settings are compatible.
UnityEngine.Debug:LogWarning (object)
Microsoft.Unity.VisualStudio.Editor.VisualStudioIntegration/<>c:<.cctor>b__6_0 () (at ./Library/PackageCache/com.unity.ide.visualstudio@2.0.18/Editor/VisualStudioIntegration.cs:55)
Microsoft.Unity.VisualStudio.Editor.VisualStudioIntegration/<>c__DisplayClass8_0:<RunOnceOnUpdate>b__0 () (at ./Library/PackageCache/com.unity.ide.visualstudio@2.0.18/Editor/VisualStudioIntegration.cs:100)
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()

languid spire
deep bear
languid spire
#

yes and the new TextAsset. Read straight into a string varaible

#

and File.Read is std C# .Net, nothing to do with unity

dusty rivet
#

does anyone know what this error means? ```Unable to use UDP port 56638 for VS/Unity messaging. You should check if another process is already bound to this port or if your firewall settings are compatible.
UnityEngine.Debug:LogWarning (object)
Microsoft.Unity.VisualStudio.Editor.VisualStudioIntegration/<>c:<.cctor>b__6_0 () (at ./Library/PackageCache/com.unity.ide.visualstudio@2.0.18/Editor/VisualStudioIntegration.cs:55)
Microsoft.Unity.VisualStudio.Editor.VisualStudioIntegration/<>c__DisplayClass8_0:<RunOnceOnUpdate>b__0 () (at ./Library/PackageCache/com.unity.ide.visualstudio@2.0.18/Editor/VisualStudioIntegration.cs:100)
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()

languid spire
#

what about that do you not understand? The message is self explanatory

dusty rivet
#

how do i fix it

languid spire
#

did you read it? It tells you

deep bear
keen dew
dusty rivet
languid spire
deep bear
dusty rivet
slender nymph
deep bear
keen dew
#

yes

dusty rivet
languid spire
deep bear
languid spire
keen dew
#

The Asset directory doesn't exist in the build so don't try to load things from it manually

dusty rivet
languid spire
#

so at some point either VS or Unity or Both asked for network permissions and you said no

dusty rivet
deep bear
#

I suppose I could use the editor instead. I was just avoiding that approach so that I wouldn't have to create an AssetLoader object and move it between scenes, but I think I should.

languid spire
#

yes, by going into the firewall and seeing which permissions are set/denied

dusty rivet
#

okay

eager elm
# dusty rivet okay

On windows, click the windows key to open the start menu, type in "firewall", open "Firewall & network protection" -> Allow an app through the firewall

dusty rivet
#

i somehow fixed it

#

i dont even know how

sour arch
#

Hi all, just me again
Trying to configure the collider on an object to hide another object when initially hit, and to recheck if its already disabled to reenable it, this is my code below. Tried creating a boolean for the object being active but i think i'm approaching it wrong. Any help is appreaciated

Cheers!

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

public class DoorHide : MonoBehaviour
{

    public GameObject Door;

    private void OnTriggerEnter2D(Collider2D other)
    {
        Door.SetActive(false);

        if(Door.SetActive(false))
        {
            Door.SetActive(true);
        }
    }
}
sour arch
#

it doesnt no, it throws me the error of "Cannot convert a void to a bool"

#

which i amended, yet its thrown me more errors lol

languid spire
#

try Door.isActiveSelf

sour arch
# languid spire try Door.isActiveSelf

Like this?


    public GameObject Door;

    private void OnTriggerEnter2D(Collider2D other)
    {
        Door.isActiveSelf

        if (Door.SetActive(false))
        {
            Door.SetActive(true);

eager elm
#

you could also use
Door.SetActive(!Door.activeSelf);

sour arch
#

Im mostly confused as this is the line that is having isues
if (Door.SetActive(false))

eager elm
languid spire
#

because SetActive returns void. activeSelf returns bool

sour arch
#

oh right

#

Im not sure how to fix that

languid spire
#

show code

cosmic quail
sterile radish
#

how do i access the value of a slider from a child of that same slider

sour arch
#
public class DoorHide : MonoBehaviour
{

    public GameObject Door;
    public bool isActive;

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (isActive)
            Door.SetActive(false);

        else _ = (!isActive);
                Door.SetActive(true);
    }

}
#

all the errors went away by doing this but uh

#

yeah, i couldn't wrap my head around the activeself tbh, I'll have to do a bit of research on it

languid spire
#

you need some basic c# syntax lessons as well

cosmic quail
cosmic quail
#

if u do it without the ! then it sets the door active only if its already active

summer stump
sour arch
#

I've been trying to self teach but I think i may have skipped just a few important bits ๐Ÿคฃ

#

my code caused me to reset to the main menu every some how?

queen adder
#

you should use events for some stuff so you dont couple stuff like MainMenu in a small component

sour arch
languid spire
#

of course it didn't, it is incomplete

sour arch
queen adder
#

should also prob do it like this:

[SerializeField]
private GameObject _door;
#

instead of public GameObject Door;

sterile radish
#

how do i set a text object's text to the value of it's slider parent

cosmic quail
summer stump
queen adder
#

Private instance fields start with an underscore (_).

sour arch
#

oh right, today's a learning day. Doing my first proper attempt at a gamejam to try and force myself to learn some of the basics (small scope game)

eager elm
sour arch
sour arch
#

so it was resetting me to the main menu

queen adder
#

ALso it prob should be like this:

[SerializeField]
private GameObject _door;
private void OnTriggerEnter2D(Collider2D other) {
     _door.SetActive(!_door.activeSelf);
}
sour arch
#

i should rework how my triggers work

#

colliders wont work here lol

#

A raycast would be overkill wouldnt it?

summer stump
sour arch
#

i meant triggers not colliders ๐Ÿ˜…

eager elm
summer stump
sterile radish
#

!code

eternal falconBOT
sterile radish
queen adder
eager elm
languid spire
queen adder
summer stump
queen adder
#

oh

#

Thats not set in convention

#

Some people have new line and some people dont

cosmic quail
queen adder
#

where

sterile radish
queen adder
#

ok

#

Use the "Allman" style for braces: open and closing brace its own new line. Braces line up with current indentation level.

#

i see

sour arch
#

does switch statements work in unity?

cosmic quail
#

yes

queen adder
#

yes

languid spire
#

of course

queen adder
#

even pattern matching i think too

sour arch
#

good, didn't want 14 statements of if and else if lol

queen adder
#
var myRes = _aInt switch {
   1 => "",
   _ => "Default"
}

or

var myRes = "";
switch(_aInt) {
 case 1: 
    myRes = "";
 break;
 default: 
    myRes = "Default";
  break;
}
sour arch
#

idk just researching it atm

eager elm
sour arch
#

trying to find better way other than if < else if < else if <etc <else

#

5 would be fine for if and else if right?

eager elm
cosmic quail
#

sounds like you need to apply some object oriented programming actually

summer stump
timber tide
#

if you're at 14 switch statements you're doing something wrong

queen adder
#

well

#

pattern matching turns into if else statements anyway under the hood

#

I think switch statements are similar too

#

after X statements it turns into a map

timber tide
#

pattern matching is just if else but prettier

sour arch
#

trial and error is the best way i learn things

queen adder
#

dw will get easier after a year

#

Just need to keep doing it ๐Ÿ˜„

timber tide
#

my python scripts usually do look pretty awful, but when it comes to runtime performance of your games you do want those micro optimizations

sour arch
#

today i managed to write myself the entire main menu funcioning script, which i was content to have learned i can do

#

just trying to push a bit

queen adder
#

I really like figma to make UI

#

Theres a plugin on unity store where it can convert figma designs to Unity components

#

Lets you worry about just the code when you import into unity instead of fiddling around with UI components trying to position them correctly

sour arch
#

||
Can this only be used once?

queen adder
#

no

#

That is equiv to a or

So:

if(aCondition || aCondition2 || aCondition3) {

}

sour arch
#

interesting, i thought so which is why i used it but this is throwing me an error

queen adder
#

Thats because you closed it too early

sour arch
#

"Invalid expression term"

queen adder
#

remove the ) inside GetComponent<Bathroom>())

sour arch
#

ohh i didn't notice that ๐Ÿคฆ

queen adder
#

Note how this is written

#

if(aCondition() || aCondition2() || aCondition3()) {

#

if( conditions )

sour arch
#

yeah, the conditions have their own brackets

quick ruin
#

Whats the hotkey to quickly move the code to the intended position?

#

you highlight and press this forgot what it was

quick ruin
#

Thanks

timber tide
#

shift tab

#

oh ctrl k, d is new to me

celest flax
#

foreach(GameObject npc in FindObjectsOfType<NPCScript>()) This gives an error cause it can't convert from NPCScript to GameObject, but how do I make it so it does work? Adding GameObject. to the start of the FindObjectsOfType<>() function didn't work and you can't add .gameObject to the end of it

eager elm
celest flax
# eager elm change 'GameObject' to NPCScript

That's what I did before, but something went wrong somewhere, so I'm just going through and changing things here and there to see if anything makes a difference. Is there no way to get the game object itself from the FindObjectsOfType<>() function?

timber tide
#

npc.gameobject

languid spire
eager elm
cerulean kestrel
#

im getting kinda used to code and im wondering if this will work. if ("Gorilla Rig") is within 5 of ("Door") play anim ("DoorOpen") then play anim ("DoorIdle")

cerulean kestrel
#

how do i fix it

#

tho

#

i kinda suck

languid spire
#

you wait until the door is open before playing door idle

cerulean kestrel
#

ok so if ("Gorilla Rig") is within 5 of ("Door") then play anim ("DoorOpen") wait until ("DoorOpen") is done play anim ("DoorIdle")

languid spire
#

yep, so now translate that into c#

cerulean kestrel
#

ok

#

ty

#

1 more thing, should i delete the default void script?

eager elm
#

if you don't need them.

cerulean kestrel
#

ok ty

#

this good?

#

ok i think i fixed it

eager elm
#

don't forget to call System.Bugs = 0 afterwards

cerulean kestrel
#

it SHOULD work now right?

celest flax
#

void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        foreach(NPCScript npc in FindObjectsOfType<NPCScript>())
        {
            if(questProgress.ContainsKey(npc))
            {
                npc.GetComponent<NPCScript>().Progress = questProgress[npc];
            }
            else            
            {
                questProgress.Add(npc, 0);
            }
        }
    }```
I'm trying to crate a script that will store some very simple quest data (Progress) when you travel across scenes. This is so that every NPC doesn't act like they see you for the first time whenever you come back from another scene. However, what I've made doesn't seem to work, even though I've confirmed it is storing its values in the dictionary. 
It seems that whenever you come back to a scene you've already been in, Unity acts like the objects in the scene are new, since it puts them into the dictionary again even if they're already there from the last time you were in the scene. Am I going about everything here the wrong way? What could I do to possibly make it work better?
languid spire
cerulean kestrel
#

or the door and the player

sour arch
#

any idea what could be causing my camera to tilt like this? (Using cinemachine)

eager elm
celest flax
cerulean kestrel
#

is this working, and should i attach it to the door or the player, ir both?

rare basin
#

umm no lol

#

go through some basic unity tutorials

cerulean kestrel
#

ive been doing that for the pst 7 hours

rare basin
polar acorn
#

I thought this was a joke

cerulean kestrel
#

not a joke

rare basin
#

you writes one if statement in 7 hours?

#

not even in Unity context?

cerulean kestrel
#

IM NOT TROLLING

polar acorn
rare basin
#

then i would say programming is not for you

cerulean kestrel
#

TUTORIALS DONT HELP

polar acorn
#

Like, even scratch would improve this

rare basin
cerulean kestrel
#

ok well 7 hours is kinda overkill

#

it was 5

polar acorn
#

Hell you could probably learn more programming reading Moby Dick

rare basin
#

this is not code suitable for Unity engine

#

!learn

eternal falconBOT
#

:teacher: Unity Learn โ†—

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

rare basin
#

@cerulean kestrel

cerulean kestrel
#

thats pretty funny, but

rare basin
#

no one will even read that

polar acorn
cerulean kestrel
#

ik i was jokin

severe drum
#

anyone knows why i cant reference my scritpableObject?

swift crag
summer stump
cerulean kestrel
#

ok ill go to gen

rare basin
rare basin
#

then go learn basic of Unity

polar acorn
swift crag
cerulean kestrel
#

oh

polar acorn
rare basin
# severe drum

any compiler errors? did you save? is the file name same as damageType?

cerulean kestrel
#

i just wanna know if it works

rare basin
polar acorn
cerulean kestrel
#

how do i make it sutiable

severe drum
swift crag
rare basin
swift crag
#

This has nothing to do with C#.

rare basin
#

!learn

eternal falconBOT
#

:teacher: Unity Learn โ†—

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

polar acorn
#

Using the links provided

cerulean kestrel
#

blah blah blah ok back to tutorials see u in seven years

rare basin
#

he is just trolling and we are all getting baited

#

just dont answer him

swift crag
#

Perhaps it includes an assembly definition to bundle all of its code together.

severe drum
polar acorn
swift crag
#

Don't put your own code into the asset's folder. Put it somewhere else.

rare basin
#

it says type or namespace

swift crag
#

So they can't see your own classes.

#

This isn't normally an issue, because third-party assets would have no clue what classes exist in your game anyway

#

(how would they know?)

severe drum
swift crag
#

Perhaps. I'm not sure what you're doing there.

#

Are you creating a new node/behavior/etc. for this system?

#

If you're trying to modify existing code, it won't be so simple.

severe drum
#

no, the health script is a LDamagable

#

but yeah i will try to jsut recreate it

severe drum
swift crag
#

If you want to modify code from the asset, then you can't move the file out of the asset's folder

#

because that change which assembly it goes into

#

and any other code that depended on it existing will not be able to see it

severe drum
#

thx for the help

sage mirage
#

Hey, guys! I want to save my audio settings in options scene when I am in play mode and when I get out to reset them back to default how to do that?

sage mirage
#

I mean I know how to save my settings but I dont know how to reset them back to default when getting out

golden otter
stuck palm
#

is a dictionary serialisable?

golden otter
stuck palm
#

zamn

#

thanks

sage mirage
#

So, I can use OnApplicationQuit to reset my settings? So, where I have my reset settings method I do have to use that inside OnApplicationQuit()?

sage mirage
#

@golden otter Does it work only for quit button or whenever I am clicking play mode on the editor?

#

or for both of them?

golden otter
sage mirage
#

I mean in my user interface I have quit button, so whenever player clicks that button to get out of the game. I want to have saved settings on my game when I am in and when getting out to reset those settings to default. That what you said doesn't work actually.

#

I tried to use that OnApplicationQuit() but nothing

golden otter
#

lemme try

#

i tried to print a log in the console when exiting the application and it works, could you show the relative code?

sage mirage
#
 {
     StartCoroutine(QuitAfterDelay());
 }


 IEnumerator QuitAfterDelay()
 {
     yield return new WaitForSeconds(quitButtonDelay);
     Application.Quit();
     EditorApplication.ExitPlaymode();
     settingsManager.ResetSettings();
     Debug.Log("Game quits and editor play mode stops!");
 }```

I have that two methods for quitting the first one is the main method and the second one is the method to quit after a delay for my button to make it look smoother.
golden otter
#

or you could use the method OnApplicationQuit

sage mirage
#

That makes sense you cannot reset settings if you have quitted already XD

queen adder
#

i generally do hold the coroutine object incase users hit StartCoroutine twice

#

.e.g.

if(_currentCoroutine != null) {
    StopCoroutine(_currentCoroutine);
}
_currentCoroutine = StartCoroutine(QuitAfterDelay());
#

in your case you most likely dont want to even stop it

#

but if(_currentCoroutine != null) return;

rare basin
#

so the user can still start the coroutine multiple time

#

it should either set the _currentCoroutine to null, or just do

if(_currentCoroutine == null)
{
    _ currentCoroutine = StartCoroutine(QuitAfterDelay());
}

this way it will start only once even if the user spams the button or whatever

stuck palm
#

can you add scripts to an object in code?

summer stump
rare basin
#

components?

#

yes

stuck palm
#

I want to make an item system where a player can pick up and drop one item at a time, and if the player drops one item onto another they get crafted into a new item. would this be a good start towards that goal?

queen adder
#

you have no abstract methods

eternal falconBOT
rare basin
#

abstract is good in this case

#

as you don't want instantiate or add just Item

stuck palm
rare basin
#

as this will be a base class for other items

#

but i wouldnt do it as a monobehaviour

#

you could do it as a scriptable object

#

sorry, you can have Item monobehaviour

summer stump
#

Agreed. Abstract poco would be good here

rare basin
#

but also can have SO like ItemData

#

where you put all the info for the item

#

name, isStackable etc

queen adder
#

Ah fair point

rare basin
#

game changing tbh

stuck palm
# rare basin name, isStackable etc

basically, the player will only be able to hold one at a time in their hands, and if they drop one onto the other it turns into another one. thats why i wanted to know if i could add or remove components, because i wanted to, say, remove the ribbon component and add a bandage component

rare basin
#

and more readable and extendable

#

and if you want to change the item name, you just go into the scriptable object of that item

#

and change it there

queen adder
#

Each item is assigned a ID

stuck palm
rare basin
#
abstract class Item : MonoBehaviour
{
   public ItemData itemData
 
   // methods
}
stuck palm
#

ohh

#

i see actually

#

that makes it a lot easier

rare basin
#

then you can acces your item.itemData.itemName etc

stuck palm
#

yeah yeah

queen adder
#

:\

stuck palm
#

that sounds good

rare basin
#

you can also make an interface for the Items @stuck palm

queen adder
#

Dont use public ItemData itemData

rare basin
#

ICraftable for example

queen adder
#

firstly your naming convention for public fields is incorrect, secondly public fields are not advised in c# convention

#

Whats ๐Ÿค” about this. Where in software do you see people using a load of public variables

rare basin
#

naming conventions are up to him

queen adder
#

Use a property over public variables

rare basin
#

he doesnt need to follow the advised c# conventions

stuck palm
rare basin
queen adder
#

And also Pascal case any public variables

rare basin
queen adder
rare basin
#

you aren't advising by saying "don't use ..."

#

you impose him to do the stuff you do

queen adder
#

please re-read

#

better teaching the correct way than doing it wrongly

#

how you are doing

rare basin
#

we need more people like you ๐Ÿ™

queen adder
#

yes and less like you teaching people to write public variables in their systems

stuck palm
#

i think public is necessary in this case because when the items interact they have to look at each other's data

rare basin
#

i didn't teach him anything dude

queen adder
#

You can use internal for this

rare basin
#

i just adapted tto his code

queen adder
#

If you want to serialize a field or property you can use the following:

[SerializeField]
private MyObject _myObject;

Or property:

[field: SerializeField]
public MyObject MyObject { get; set; }
rocky canyon
#

why use unity at all?

rare basin
#

i just guided him based on his code and actually helped him, instead of moaning like you, please cut the talk

rocky canyon
#

just code ur own engine

rare basin
#

yea

queen adder
#

This way you can have a public property

thorn fossil
#

Hi, I'm having this problem using NavMeshPro :

"SetDestination" can only be called on an active agent that has been placed on a NavMesh.

Here is my class

using UnityEngine;
using UnityEngine.AI;

public class PhantomScript : MonoBehaviour
{
    private NavMeshAgent agent;
    [SerializeField] Transform target;

    private void Start()
    {
        agent = GetComponent<NavMeshAgent>();
        agent.updateRotation = false;
        agent.updateUpAxis = false;
        agent.isStopped = true;
    }

    private void Update()
    {
        agent.SetDestination(target.position);
    }
}

And there is my object :

thorn fossil
#

yes

rare basin
#

and is your agent placed on actual navmesh?

thorn fossil
rare basin
#

that doesn't show anything

#

show the surface with baked navmesh

#

and the agent on it

thorn fossil
thorn fossil
queen adder
#
agent = GetComponent<NavMeshAgent>();
        agent.updateRotation = false;
        agent.updateUpAxis = false;
        agent.isStopped = true;

Are you sure isStopped = true is not causing a issue?

thorn fossil
#

I sent the wrong one my bad

rare basin
#

show me the object in the scene view

rare basin
thorn fossil
rare basin
#

and where's the agent? this red dude?

thorn fossil
#

yes

rare basin
#

did you import the navmesh 2d package

#

or 3d one?

#

is the game 2d or 3d

#

if it's 2d you need NavMeshSurface2D

#

attached to the surface

thorn fossil
#

Yeah but I'm using NavMeshPro not the Unity one

rare basin
#

then i have no idea if this asset supports 2D navmesh

thorn fossil
#

I think so

#

I'm gonna try the Unity one

rare basin
#

why not just use the unity built-in one

thorn fossil
#

Yeah thanks you

rare basin
thorn fossil
#

It's the same lib he's just using an older version

rare basin
#

no he's using a 2D package

#

and the asset you have probably is made for 3D only

#

if there is no NavMeshSurface2D component

queen adder
#

@thorn fossil try to remove that isStopped = true and see if it works?

rare basin
queen adder
#

The changeDestination docs clearly say navmeshagent should be active

#

Nothing hurts in enabling it

#

and seeing if it works

rare basin
#

SetDestination()*

thorn fossil
rare basin
#

its not

#

he's using NavMeshPlus downloaded from github

#

not NavMeshPro from asset store

thorn fossil
#

"com.h8man.2d.navmeshplus": "https://github.com/h8man/NavMeshPlus.git#master"

This is from my manifest.json ...

rare basin
#

you said you are using NavMeshPro

thorn fossil
#

I miss named it :/

queen adder
#

it just say hi on console

rare basin
#

!code

eternal falconBOT
rare basin
#

are you sure that OnTriggerEnter is called at all?

#

anyway, your collider is not set to isTrigger

queen adder
#

and touches it

rare basin
#

does your player has collider with isTrigger and a rigidbody?

#

put a debug log in the ontriggerenter to see if its even called at all

thorn fossil
#

I found why it was buggy, the pos Z was like so far away from everything else ๐Ÿ˜‚

#

It was just that

rare basin
#

nice!

queen adder
#

@queen adder like this?

rare basin
#

!code

eternal falconBOT
rare basin
tidal swift
#

Ive made a moveable character on 3d, i used my own script didnt use charactercontroller, so I can walk on the default Terrain unity provides but when I create a 3d square object to test, my player wont move at all

I do have rigid body on my player, the square also has box collider any ideas ๐Ÿค”

queen adder
rare basin
rare basin
#

because i doubt it, your collider is not set to isTrigger

queen adder
#

i added hi wassup

#

if it says hi wassup on colse

#

it means it called?

rare basin
#

please