#💻┃code-beginner

1 messages · Page 86 of 1

craggy bane
#

and destroy them*

scenic cipher
#

Are you iterating a list or transform?

craggy bane
#

transform

scenic cipher
#
foreach (Transform obj in parentTransform)
{
    Destroy(obj.gameObject);
}```
craggy bane
scenic cipher
craggy bane
#

I put the objects which have animations on them in a empty parent and now the animations aren't working??

rich adder
craggy bane
#

so they gotta be seperated?

rich adder
#

you need animator

craggy bane
#

oh on the parent?

rich adder
#

put the animations in the Animator controller on parent

vital spade
#

hello people, I have another small issue, I'm trying to delete a "grid" from the hierarcy but for some reason I cannot? right click delete or pressing delete from the keyboard does not work, any ideas why that may be the case?

vital spade
formal escarp
#

hey guys. can 1 game object have more than 1 tag?

formal escarp
#

oh. okay

pallid verge
#

I wanna make my button change color from red to green when clicked and reverse. i tried this but it didnt work

#

maybe instead of Color.--- i should put the hex code?

wintry quarry
pallid verge
royal ledge
#

oy, i have a maincamera that is in a secondary scene added additively. But now i want a canvas that has screen space camera in the main scene, but then i can't reference the maincamera across scenes. Are there any workarounds? I despise screen overlay, specially because i animate stuff and then i don't have a reference to the main scene because it is so huge compared to the actual scene

wintry quarry
#

Use debug.log

rich adder
pallid verge
wintry quarry
pallid verge
#

with debug.log

#

as you told me

wintry quarry
royal ledge
#

Ah camera.main works across all scenes?

pallid verge
wintry quarry
pallid verge
solemn fractal
#

!code

eternal falconBOT
pallid verge
solemn fractal
#

Hey guys, I have this GameManager script where I save the player progression when he dies and reload the scene. What happens is that if I die and reload the scene its fine, works good. But if I am killing the final boss of the mini game, and I die and the scene is reloaded, all the enemies desappear but not the boss, what could be? https://paste.ofcode.org/x5Tkj3nx55nAee5mvDBgnD

rich adder
eager elm
pallid verge
rich adder
#

its probably neither when you run that function

pallid verge
rich adder
#

how ? it doesnt change by itself lol

#

try putting buttonImage.color = Color.red

#

in start for example

#

and see if function works after

pallid verge
#

it works

#

thank u

rich adder
minor roost
#

!code

eternal falconBOT
minor roost
royal ledge
#

@wintry quarry @rich adder lol this worked, my bad thought i had tried something similiar in the past, ty a bunch

craggy bane
#

Hi I finished a wave script and found out about animation rebinding can someone explain what it is to a beginner?

#

Right now cloned objects spawn but I want them to move like I assigned their original to move

rich adder
royal ledge
#

void Start()
{
myCanvas.worldCamera = Camera.main;
} xDDDD

autumn tusk
#

how do i use constraints in unity 2d to freeze a moving bullet on collision with an object

rich adder
eternal needle
autumn tusk
#

i have my collision code setup

rich adder
#

ok so whats the problem

#

OnCollisionEnter2D + rb.contrains =

solemn fractal
autumn tusk
#

this is what i have right now

#

not sure what syntax im supposed to use for this

rich adder
#

this^ also pretty sure once you type = VS will show you all the proper enum options

autumn briar
#

How can I change the player's Y rotation to be the same as the cam's Y rotation? I tried setting the rotation directly but it doesn't work

#

I used Cinemachine to make a FP cam

autumn briar
#

what do you mean? cause I tried transform.rotation.eulerangels = cam.transform.rotation.eulerangles but it didn't work

eternal needle
autumn tusk
rich adder
#

2D doesn't rotate on X

polar acorn
solemn fractal
autumn tusk
rich adder
autumn briar
eternal needle
polar acorn
autumn tusk
#

alright, it just rotates based on a single digit

#

freezerotation does the trick

rich adder
# autumn briar yes

think you can do something like

var myRot = player.rotation.localEulerAngles;
myRot.y = cam.rotation.localEulerAngles.y
player.rotatation = quaterion.euler(myrot)```
queen adder
#

hi guys, wanna make a game but still not too experienced. wanna make a game that basically looks like command prompt, and it asks you questions like age, name, etc. and predicts your future, wanna make it an analogue horror game and when the game says "when your going to die:" it says tomorrow, flashes a name and closes. tried to find a tutorial but cant really find anything

buoyant knot
#

if your whole game is in a command prompt, then unity is not the right engine for you

queen adder
#

ah okay, what can i use?

buoyant knot
#

you don’t need a gameengine for that tbh

queen adder
#

wanna add vhs and background stuff to make it even more scary

buoyant knot
#

idk, but i still don’t think Unity is the right tool for this

autumn tusk
queen adder
#

honestly true, mb

buoyant knot
#

yeah. pygames is probably a good start

autumn tusk
#

pygames really good for multiple windows and stuff like that

rich adder
#

💩

queen adder
#

alright ty

timber tide
#

pygames is aight but you can also just make it in c# without unity

#

assuming you want to use unity later lol

rich adder
#

C# is king

#

but if python works for you do that :p

queen adder
#

aight

#

ty

safe carbon
#

how can i download autofiller for visual studio

#

i forgot how

rich adder
#

what the hell is that lol

safe carbon
#

umm like gives you options when ur almost done with writing the word

#

idk how explain it

#

not really necessary ig just see some people have it

rare basin
#

!ide

eternal falconBOT
rich adder
#

or copilot

#

depending which one they have

scenic cipher
#

@safe carbon I believes its in the Visual Studio Installer, Click Modify, then install the "Game development with Unity"

rich adder
#

intellicode is kinda copilot lite

#

follow the IDE config

#

it will work

safe carbon
#

Thank you good sirs

rich adder
#

dont crosspost

#

also this alone isn't helpful to anyone willing to help, you haven't even posted the code with it

smoky niche
#

The code is not necessary, as it's a tilemap collider bug

rare basin
#

then why are you posting this

#

in a code related channel

rich adder
#

then why are you in a code channel

#

posting in multiple code ones none other

smoky niche
#

Apologies, where should I best go with this question?

#

Thanks

minor roost
#

void generateTree(float x, float y)
{
//Define tree

    //Generate Log
    int treehieght = Random.Range(minTreeHieght, maxTreeHieght);
    for (int i = 0; i <= treehieght; i++)
    {
        placeTile(LogTrunk, x, y);
        placeTile(Log, x, y + i);
    }
   
    //Generates Leaves
    placeTile(Leaf, x, y + treehieght);
    placeTile(Leaf, x, y + treehieght + 1);
    placeTile(Leaf, x, y + treehieght + 2);

}
#

It places like 7 logtrunks

rich adder
#

so what is treehieght

#

not even sure what this code snippet alone does

minor roost
#

its hieght of tree

rich adder
#

i see a leaf lookin like a triangle or sum

minor roost
#

want full code

rich adder
#

well no guarantee I can be of help but at very least post the whole script maybe someone knows

#

!code

eternal falconBOT
minor roost
rich adder
minor roost
#

when placetile happens with log trunk

#

7 log trunks place inside one place tile

rich adder
#

well yeah you never increase by i

#

which way is supposed to spread?

#

your x y stay the same why would it not spawn in same spot lol

minor roost
#

lol

#

so hows it supposed to look like

rich adder
#

you tell me

#

what is Log vs Log Trunk ?

minor roost
#

log trunk is bottom

#

log is middle

rich adder
#

so you only need 1 put it outside the loop

#
            placeTile(LogTrunk, x, y);
for (int i = 0; i <= treehieght; i++)
        {

            placeTile(Log, x, y + i);
        }
       
        //Generates Leaves
        placeTile(Leaf, x, y + treehieght);
        placeTile(Leaf, x, y + treehieght + 1);
        placeTile(Leaf, x, y + treehieght + 2);
minor roost
#

TY XD

rich adder
#

or actually make it only place it if its first iteration

#

this way your placetile log doesn't run first iteration

#

you dont want a log inside a trunk log

minor roost
#

ty

rich adder
#
for (int i = 0; i <= treehieght; i++)
        {
            if(i == 0){
              placeTile(LogTrunk, x, y);}
            else {
              placeTile(Log, x, y + i);}
            }
       
        //Generates Leaves
        placeTile(Leaf, x, y + treehieght);
        placeTile(Leaf, x, y + treehieght + 1);
        placeTile(Leaf, x, y + treehieght + 2);```
hidden sun
#

hi, how can i use the polygon collider to see if its collide with another object?

#

i can't find an example on google

rich adder
#

OnCollisionEnter2D

#

you need at least 1 rigidbody between the two collisions

hidden sun
#

so i need to add rigidbody on it

rich adder
#

either this one or the one you are colliding with

#

also depending if you want Collision or just a Trigger

hidden sun
#

Trigger

#

so i should use OnTriggerEnter2d

rich adder
#

if you dont want that shape to be solid

#

use trigger

hidden sun
#

ty

rich adder
hidden sun
#

2 static rigidbody so i think it will be ok

slender nymph
#

incorrect. notice how static trigger and static do not produce a trigger message

#

nor does static trigger and static trigger

rich adder
hidden sun
#

so i need a non rigidbody and a rigidbody

rich adder
#

like I said before , no you only need 1 rigidbody between two colliders

slender nymph
#

i would also like to point out that trigger/collision messages will not tell you if the object entirely overlaps the other object as was your goal the other day

hidden sun
#

yes, but that is a lil bit hard.. because i have the same object

#

both objects use the same prefab

rich adder
real void
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

hidden sun
#

overlaps

slender nymph
#

why

autumn tusk
#

how do i get an animation to change states on collision via the animation controller

hidden sun
#

its a rule that the plane can't overlap

slender nymph
#

your overlap points can get you that info

#

if they don't hit anything or if they hit another plane object then they cannot be placed, it's that simple

autumn tusk
#

how do i define a parameter for the animation controller

open adder
#

why i dont see the spotlights / lights in game but in editor yes

slender nymph
#

this is a code channel

minor roost
#

how could i make sorting order of leaves 1

#

void generateTree(float x, float y)
{
//Define tree

    //Generate Log
    placeTile(LogTrunk, x, y);

    int treehieght = Random.Range(minTreeHieght, maxTreeHieght);
    for (int i = 0; i <= treehieght; i++)
    {
        placeTile(LogTrunk, x, y);
        placeTile(Log, x, y + i);
    }
   
    //Generates Leaves
    placeTile(Leaf, x, y + treehieght);
    placeTile(Leaf, x, y + treehieght);
    placeTile(Leaf, x, y + treehieght + 1);
    placeTile(Leaf, x, y + treehieght + 2);
    placeTile(Leaf, x, y + treehieght + 3);

    
    placeTile(Leaf, x - 1, y + treehieght);
    placeTile(Leaf, x - 1, y + treehieght + 1);
    placeTile(Leaf, x - 1, y + treehieght + 2);
    
    placeTile(Leaf, x - 2, y + treehieght);
    placeTile(Leaf, x - 2, y + treehieght + 1);

    placeTile(Leaf, x + 2, y + treehieght);
    placeTile(Leaf, x + 2, y + treehieght + 1);

    placeTile(Leaf, x + 1, y + treehieght);       
    placeTile(Leaf, x + 1, y + treehieght + 1);
    placeTile(Leaf, x + 1, y + treehieght + 2);

}
slender nymph
#

!code

eternal falconBOT
minor roost
slender nymph
#

if your goal is to change the sorting order of your tiles, that is done on the TilemapRenderer not individually per tile

minor roost
#

of the leaves

#

how then?

slender nymph
#

if you want them to have a different sorting order than the other tiles, then put them on a separate tilemap and change the sorting order for that tilemap

craggy bane
#

How do I stop an object from animating if it's not shown on the scene

#

Everytime I click this UI button I set the object animates

#

But I want it to animate only when it pop ups

timber tide
#

disable the gameobject it's on until you need it

#

or do you mean it's not reset when you renable it

#

may need to play() again when you activate it

rich adder
#

or put empty state as default starting state

short hazel
#

Animator's Culling options in the Inspector. I think it stops animating when the object is not visible by default

#

Not sure if it works with UI

craggy bane
rich adder
#

no

ruby python
#

Just troubleshooting something and just wanted to double check.....

Am I using this correct to assign the parent of an object to another object variable?

GameObject doorToRemove = doorChecker.transform.parent.gameObject;

rich adder
#

you just need a way to play your animations though (either transition or call Play)

craggy bane
rich adder
humble lantern
#

Hey, I'm trying to scale a UI image by a factor of two but so far setting the size of the gameobject with image.rectTransform.sizeDelta = new Vector2(128f, 128f); hasn't worked and I'm not sure what else would, is there some common way of doing this?

craggy bane
#

or triggering

rich adder
#

show it

craggy bane
#

Ok

safe carbon
#

yo quick question

#

if(mouseP.x > 720 && mouseP.x < 780) {
transform.eulerAngles.z = -48.068f;
}

#

i am trying to set the orientation of a sprite

#

dont want to add rotation to it cause when i use transform.rotate it keeps adding up

#

i want to set a orientation

short hazel
#

Those numbers are oddly specific, but anyway

#

transform.rotation = Quaternion.Euler(x, y, z) is how you assign a new rotation with angles in degrees

safe carbon
minor roost
#

how do i make tile order 1 for leafs

rich adder
minor roost
short hazel
slender nymph
#

why not

minor roost
#

i dont know how to do it it gave errors

stuck palm
#

how can i balance my physics based movement code so it feels snappy? right now my character is sliding around a bunch and the gravity is very low for some reason so it doesnt feel very responsive

slender nymph
#

ah yes, it gave errors. and we're supposed to know what those errors are?

solemn fractal
#

Hey guys, I have 2 scenes. in the first scene I have the player on the hierarchy always. and in the second scene I want to be able to access that player. how can I do that? I tried on the second scene assigning on the inspector the player prefab as serializedField Player player; but its not working. Is there a method to fetch things on the other scene?

rich adder
#

singleton

minor roost
short hazel
slender nymph
minor roost
#

i dont know how to script c++

slender nymph
#

and for future reference, share your errors. don't expect others to just immediately know what they are (even though in this case I did)

slender nymph
safe carbon
minor roost
#

dam

slender nymph
#

and if you don't understand how to code, there are beginner courses pinned in this channel

short hazel
slender nymph
#

then start with the beginner c# courses pinned in this channel

slender nymph
#

why not just multiply/divide its localScale by 2?

humble lantern
#

with something like image.rectTransform.localScale = image.rectTransform.localScale * 2;?

rich adder
#

big brains use *= or /=

#

so we don't write DRY code

humble lantern
#

that works?!

#

i have so much to learn

rich adder
#

yeah so instead of a = a +b
you can just do a+=b

humble lantern
#

ohh I only ever encountered a++ for incrementing

wintry quarry
#

it works sure, it's identical. To avoid floating point precision issues I'd probably do something like this though:

Vector3 originalScale;

void Awake() => originalScale = image.transform.localScale;

void Shrink() {
  image.transform.localScale = originalScale / 2;
}
void Normal() {
  image.transform.localScale = originalScale;
}
void Grow() {
  image.transform.localSale = originalScale * 2;
}
rich adder
#

yea much better than dealing with transform values

runic dome
#

Hi ! I have a some problem with my code.

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

public class PlayerInputManager : MonoBehaviour
{
    public static PlayerInputManager instance;
    PlayerControls playerControls;

    [SerializeField] Vector2 movementInput;

    private void Awake() 
    {
        if(instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
        
    }

    private void Start()
    {
        DontDestroyOnLoad(gameObject);

        SceneManager.activeSceneChanged += OnSceneChange;
        
        instance.enabled = false;
    }

    private void OnSceneChange(Scene oldScene, Scene newScene)
    {
        if (newScene.buildIndex == WorldSaveGameManager.instance.GetWorldSceneIndex())
        {
            instance.enabled = true;
        }
        else 
        {
            instance.enabled = false;
        }
    }
    private void OnEnable() 
    {
        if(playerControls == null)
        { 
            playerControls = new PlayerControls();

            playerControls.PlayerMovement.Movement.performed += i => movementInput = i.ReadValue<Vector2>();
        }

            playerControls.Enable();

          
    }
      private void OnDestroy() 
{
    SceneManager.activeSceneChanged -= OnSceneChange;
}

}

and this is my error :
Type 'PlayerInputManager' already defines member called 'OnDestroy' with the same parameter types

wintry quarry
runic dome
#

oh..

wintry quarry
#

not only that but PlayerInputManager is a bad name in the first place because Unity's input system already has such a class, which will be confusing

runic dome
#

ok ok i'll fix that

runic dome
#

ohh ok.

#

thanks you !

steep mist
#

i have no idea what this is telling me. i've looked over my code and compared it to what i was following and cannot tell what i did wrong

#

lemme go grab screen shots and then a copy of my code

slender nymph
#

you cannot subtract arrays

steep mist
#

i'm sure its a syntax or spelling error somewhere but i cannot see it

slender nymph
#

configure your !IDE

eternal falconBOT
steep mist
slender nymph
#

you are, but you don't mean to

steep mist
#

in what way? is it because zero is typed instead of numerical?

slender nymph
#

no, configure vs code and it will underline the line with the error and maybe you'll see your mistake

steep mist
#

configure it how? i had VS installed for coding class already and it doesnt show me an error

slender nymph
rich adder
#

its as good as a text editor right now

steep mist
rich adder
#

doesn't matter Unity has their own workload

steep mist
#

and many other coding languages so it should be fine

rich adder
#

configuration is laid out in the link, they are very important steps

#

they are particular to unity

rich adder
slender nymph
#

your issue is literally caused by a typo that a properly configured IDE will point out to you

steep mist
rich adder
#

Unity has no native language

#

its just C#

#

but C# configuration for unity is different

#

because unity uses old ass .net

runic dome
#

Hi ! idk where to post this so i post here. This is the code of my script (nothing in it)

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

public class NewBehaviourScript : MonoBehaviour
{
    
}

When i'm trying to put the script to the component of my player, this is the "error" i'm having

#

(ofc if i didn't post this in the good place just tell me and i will delete this message)

slender nymph
#

do you have any compile errors?

rich adder
#

file doesnt match class name

slender nymph
#

also that

rich adder
#

where is console window lmfao

runic dome
rich adder
#

oh wait nvm

#

i see it, no errors

slender nymph
#

man that layout is wack, i didn't even notice the console under the hierarchy lmao

rich adder
#

fr

slender nymph
rich adder
#

I thought mine was bad , turns out im wrong haha

runic dome
#

as bad as mine

rich adder
#

nah if it threw me off too its bad xD

#

anyway your file must always match class
mycoolfile.cs
public class mycoolfile

#

ofc don't use lowercaps cause its nasty

runic dome
#

like this ?

neon ivy
#

mostly a question about convention instead of an actual problem.
I have a scriptable object CharacterData and another one called CharacterLibrary to make getting data from specific characters easier.
in CharacterData I have methods GetPortrait() and GetAudioProfile().
would it be smart to give the CharacterLibrary methods GetCharacterPortrait() and GetCharacterAudioProfile to use these get methods from the library?
or should I just do GetCharacter().GetPortrait() in my code?

slender nymph
runic dome
slender nymph
cyan pike
#

I'm trying to make a connection with MySql to store the scores in a DB, but I'm having difficulty installing the MySQL plugin in the project. So far I have added the .dll to the assets and changed the API Compatibility Level to .NET Framework

rich adder
#

also why not SQLite plugin

#

SQLite is dope

neon ivy
rich adder
#

should never have connections to a database in your client/game

slender nymph
cyan pike
slender nymph
neon ivy
#

I could see either way working, though I agree that the library shouldn't care about the properties of data holders so I'll keep the methods in the character data UnityChanThumbsUp

fluid kiln
#
using UnityEngine;

public class Movement : MonoBehaviour
{
    // Data
    public Animator animator;
    public float moveSpeed = 5f;
    public Rigidbody2D rb;
    public Vector2 movement;
    Vector2 lastMovement;
    public bool isCasting = false;

    void Update()
    {
        // Get input for movement
        float horizontalInput = Input.GetAxisRaw("Horizontal");
        float verticalInput = Input.GetAxisRaw("Vertical");

        // Calculate movement vector
        movement = new Vector2(horizontalInput, verticalInput).normalized;

        // Check if the character is moving
        bool isMoving = (movement.magnitude != 0);

        // Set animator parameters for movement
        animator.SetFloat("Horizontal", horizontalInput);
        animator.SetFloat("Vertical", verticalInput);
        animator.SetFloat("Speed", movement.sqrMagnitude);

        // Set facing direction when idle
        if (!isMoving)
        {
            // Use the last movement direction when idle
            animator.SetFloat("IdleHorizontal", lastMovement.x);
            animator.SetFloat("IdleVertical", lastMovement.y);
        }
        else
        {
            // Update last movement when moving
            lastMovement = movement;
        }
    }

    void FixedUpdate()
    {
        // Move the character
        rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
    }
}

feel like there's something wrong with this, its attached to an animator that gets the horizontal and vertical axis in wasd movement, and its saving the axis to display the right idle animation too when the character is still, but i feel like its wrong

eternal falconBOT
rich adder
#

large code should be links

steep mist
#

well i followed the instructions and downloaded Cs and the unity vs code, even changed unity's preferences to match but now its telling me i don't have .NET

slender nymph
#

restart the computer if you just installed it and it's still not recognizing that you have the sdk

steep mist
#

mk, restart it is. brb

neon ivy
crude prawn
rich adder
#

had to do this recently , somehow vscode wasnt downloading it

neon ivy
#

wrong personUnityChanHuh

rich adder
#

my bad yes

neon ivy
#

np np

fluid kiln
neon ivy
#

sorry can't help with animator hell, I don't use it that way xD I just do animator.Play() most of the time

fluid kiln
#

oh, thank you!

fluid kiln
steep mist
#

it probably doesnt help that i've installed unity onto another drive to save space. if i need to i'll install .net8 directly to that drive and that project

rich adder
steep mist
rich adder
neon ivy
steep mist
#

i would hope not, but i do know fixing directory issues is a beast

#

at least for me

rich adder
#

once it opens the solution then you know it works

fluid kiln
neon ivy
#

yes

rich adder
#

after you install .net You'd have to try regen project files in Unity again (assuming you did install the update for the VSEditor package) @steep mist

fluid kiln
#

i spent so much time in it today

#

trying to make it work for sprites reee

slender nymph
#

you'll see the option in one of the locations you had to do something when configuring vs code 😉

steep mist
#

also this is the correct one right?

slender nymph
#

yes

steep mist
#

at least from visual studio

slender nymph
#

a different set up to what? vs code? because i was referring to the instructions for vs code

rich adder
#

but its very picky about it

summer stump
neon ivy
# fluid kiln amazing also kinda pain T-T

I'd say, do something like this:

public enum Directions
{
  North,
  East,
  South,
  West
}
[SerializeField] private Directions direction
public Directions Direction
{
  get
  {
    return direction;
  }
  set
  {
    if(direction != value)
    {
      direction = value;
      anim.Play(direction.ToString());
    }
  }
}
slender nymph
compact dirge
#

very quick dumb question
i have a transform.position
I want that point + 2 on y
what i should write?

slender nymph
summer stump
compact dirge
#

well what navarone said lol
i was wandering if there is a way other then adding a new vector3

compact dirge
#

just for not create a new one and just add 2 to the previous location

steep mist
compact dirge
#

nothing important tbh

#

but good to know

rich adder
#

its 3 floats but fancy

compact dirge
#

oh wait true

cosmic dagger
compact dirge
#

my b

summer stump
slender nymph
steep mist
#

well i think then i've done everything, but it still wont debug in vs code

slender nymph
#

you don't need to be using the debugger for this, you just need it configured to see your simple typo

#

but if you cannot get vs code configured, then consider switching to a real IDE that is less likely to be fucked up like visual studio

slender nymph
steep mist
slender nymph
#

go through all of the steps again and you'll see it if you've done it correctly

rich adder
#

the big button that said Regeenrate Project Files in the preferences step

steep mist
#

by regenerate does that mean open the files associated with the project in vs code

slender nymph
#

no

#

there is a button that literally says Regenerate Project Files

#

and i am intentionally not telling you where it is because you've clearly missed steps in the configuration so you need to go through it

rich adder
#

ill delete my msg 🙂

compact dirge
#

Debug.DrawRay(transform.position, (transform.position + new vector3(0, 2, 0)) , Color.red);
gives me that can't find the vector3 namespace 🤨

eternal falconBOT
slender nymph
#

your parameters for your Debug.DrawRay are also incorrect, the second parameter takes the direction and length, not the end point

rich adder
steep mist
#

ooh i see it now, the web page given didnt say anything about it though it probably should have added that in

#

"for users who already have scripts press regenerate"

craggy lava
#

Hi so i have this script i just dont know how i should like hold the object I am making like a gravity / physics tool and rn i am trying to make it so you can pickup an object and rotate it when holding CTRL and move it in and out using scroll wheel but rn i am stuck on the pickup thing idk how to make it pickup the object i have a PickupPoint Empty Game Object infront of my player here is my script

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

public class GravityTool : MonoBehaviour
{
    [SerializeField] private Camera playercam;
    [SerializeField] private Transform holdPos;
    [SerializeField] private LayerMask pickupLayer;
    [SerializeField] private float pickupRange;
    private Rigidbody currentObj;

    private void Update()
    {
        Ray ray = playercam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
        RaycastHit hit;
        if (Input.GetKeyDown(KeyCode.E))
        {
            if (Physics.Raycast(ray, out hit, pickupRange, pickupLayer))
            {
                currentObj = hit.rigidbody;
                currentObj.useGravity = true;
            }
        }
    }
}
rich adder
#

yeah they assume everything goes right @steep mist

steep mist
#

or something like that

compact dirge
slender nymph
#

where does it say that?

compact dirge
#

Declaration
public static void DrawLine(Vector3 start, Vector3 end, Color color = Color.white, float duration = 0.0f, bool depthTest = true);

wintry quarry
#

Not DrawRay

steep mist
#

how will i know if this "worked"? i pressed it and no icon indicated it did anything

compact dirge
#

...oof

#

i'm so dumb

slender nymph
steep mist
#

alrighty

dry tendon
#

!code

eternal falconBOT
steep mist
#

still no red line. i think i'll save, close and re open the whole project and if need be do another restart

slender nymph
#

you probably want to disable gravity when picking it up, rather than trying to enable it again. you should probably also be parenting the picked up object to the PickupPoint object

dry tendon
rich adder
#

open the Output tab

dry tendon
slender nymph
#

how have you confirmed that the condition is correct and that it is evaluating to true?

floral trail
#

I making a claw machine game and I’m using the timeline to drop and raise the claw, how can I make the animation just change the y axis instead of setting the claws position to the x and Z positions in the recorded timeline?

summer stump
craggy lava
rich adder
#

also ur in a code channel

dry tendon
slender nymph
#

huh?

dry tendon
slender nymph
#

don't make assumptions about what is happening. you need to verify

steep mist
#

finally all that to realize it was not an = sign

slender nymph
#

yep

steep mist
#

at least i finally have debugging set up correct

rich adder
#

its working now ?

steep mist
#

yeppers

rich adder
#

good!

steep mist
#

finally! woo

slender nymph
#

and now you will be much less likely to make simple typos like that in the future

steep mist
#

precisely

rich adder
#

now VSCode is somewhat of an IDE and not just text editor

summer stump
steep mist
slender nymph
steep mist
#

lol flarpy birb

slender nymph
#

i'd bet either their variable for the impulse is 0 or their rb is kinematic or something simple like that

#

unless the condition is not true

steep mist
#

imma get back to it, goodluck with gravity

rich adder
#

at least use Typescript xD

summer stump
dry tendon
#

that's not the prob

slender nymph
summer stump
dry tendon
#

a minute ago it worked correctly... it sounds weird hehe, but i don't know what i have touched

dry tendon
summer stump
dry tendon
slender nymph
#

where is the rigidbody

summer stump
#

Impulse is pretty low too
Depending on the mass and gravity

dry tendon
neon ivy
summer stump
#

Eh, should be fine value to only go a little.

dry tendon
summer stump
slender nymph
#

have you added any useful logs to determine that the code is being executed?

dry tendon
slender nymph
#

that is not useful in any sense of the word

dry tendon
#

definetly that log works

summer stump
cosmic dagger
#

The bird is the word . . .

slender nymph
dry tendon
#

but then jump stops working

fluid kiln
slender nymph
dry tendon
safe carbon
#

So i am thinking of making it so once you click a station character faces that specific stations and shoots out to it. Having hard time with the orientation where it faces selected station. So i was wondering what do you guys think i need to learn to accomplish this, not how but what

#
  • get the position of the selected station so it can face it basically
slender nymph
slender nymph
dry tendon
dry tendon
#

or you mean like this?

safe carbon
#

What does .normalized do

dry tendon
neon ivy
slender nymph
#

so if the object is not jumping then either your force is too low, or something else (like controlling the position via animation) is preventing it from jumping

slender nymph
polar acorn
safe carbon
#

oh ok

runic dome
#

Hi, I have a syntax error that I'm trying to find for 2 hours now, idk if i can post the code here

eternal falconBOT
slender nymph
#

also if you cannot see it underlined in red in your !IDE then you need to get it configured

eternal falconBOT
runic dome
slender nymph
slender nymph
slender nymph
#

okay well then you will get help with your syntax errors tomorrow

runic dome
#

sure !

#

have a nice evening guys

blissful heart
#

im haivng some issues thats its going to make me punch the f*** screen lmao

#

for some reason the buttons are not working

#

its interactable, its on the canva, theres nothing on top of the button

#

i really think the Unity is bugged, i already restarted the PC and nothing. Really strange... im getting so pissed off about this lmao

#

why this is happening..

safe carbon
#

is it just transform.right = direction;

#

or transform.right is executed differently

modest dust
#

Also, make a new button, don't change anything and check if that's pressable

#

From there just change one thing after another to see what's the issue

#

Idk if the 4.6 scale doesn't have to do something with this

blissful heart
modest dust
#

It's neither probably since it's not code, lol

#

But as I said, make a fresh new button, which should work out of the box

#

If that's not pressable then there's something blocking it

blissful heart
#

still not clickabl

#

the canva is at 5 layer, how its blocked?

#

blocked from what?

modest dust
#

Something else in the scene, but if there's nothing there then idk

#

Just made a button on layer 5 in my project and it works without any issues

#

I might be missing something tho since I rarely use the built-in button

steep mist
#

can someone see where i went wrong in this code. its supposed to render 6 sides of a cube but its only rendering one side

modest dust
blissful heart
#

for some reason its that scene the problem

modest dust
#

Then probably something in your scene is "blocking" your press

modest dust
#

disable one thing after another

#

or disable everything and bring back one thing after another

#

that should give you the answer

blissful heart
#

bruh idk wth is going on lmao i removed everything and still not working, its some canva config for sure

blissful heart
modest dust
#

Not sure, I'm not that good with UI

#

Try playing around with settings / compare it to a fresh new canvas

scenic cipher
#

@blissful heart Do you have an EventSystem? I dont see one in your hierarchy.

blissful heart
#

you are goddamn right

#

I got one now and its working

#

Thanks a lot @modest dust for the help and @scenic cipher

scenic cipher
#

You're welcome

blissful heart
#

i guess i removed the eventsystem by accident dk

modest dust
#

Ah yes, EventSystem, makes sense

scenic cipher
blissful heart
#

now its time for 100x ctrl+z and continue progress hehe

dry tendon
dry tendon
blissful heart
#

haha yeah just like me rn

#

i've been like 1h trying to click the f button

#

and it was just the eventsystem lmao

#

this discord helps a lot

slender nymph
dry tendon
#

Now and then i'll check that at first hehe

hushed rose
#

Is possible to turn on / off avatar mask parts from script?

tender stag
#

why doesnt this work?

#

it still prints the object the script is on to the console

#

i did this

rare basin
#

just cache the reference to the owner

#

if you change hierarchy it wont work

tender stag
#

wdym

#

the collider isnt on the same transform

rare basin
#

so what, just cache the owner

tender stag
#

what

fierce shuttle
tender stag
#

it works not its fine

unreal imp
#

How could I make scaling a parent object not affect its child object?

queen adder
#

having issues with netcode for gameobjects and lobbies, I don't understand how to resolve this error? ```public async void JoinLobbyByCode(string lobbyCode)
{
try
{
player = playerNameText.text;
JoinLobbyByCodeOptions joinLobbyByCodeOptions = new JoinLobbyByCodeOptions
{
Player = new Player
{
Data = new Dictionary<string, PlayerDataObject>
{
"PlayerName", new PlayerDataObject(PlayerDataObject.VisibilityOptions.Member, player)
}
}
};
Lobby joinedLobby = await Lobbies.Instance.JoinLobbyByCodeAsync(lobbyCode, joinLobbyByCodeOptions);

        Debug.Log("Joined Lobby with code" + lobbyCode);

    } catch (LobbyServiceException e)
    {
        Debug.Log(e);
    }

}```
gritty roost
#

these beginners 🤦🏽

mild lake
#
GameObject obstaclePrefab = obstacles[Random.Range(0, obstacles.Length)];

float colliderHeight = obstaclePrefab.GetComponent<BoxCollider2D>().bounds.size.y;

Does anyone have any idea why this is returning only zero? My object has a proper boxCollider2d set up

slender nymph
queen adder
mild lake
slender nymph
agile oriole
#

Hello, I have this sprite, which, as you can see, has a gun that's not in the center of the sprite (along the y axis). I currently have this code to rotate my player towards the mouse cursor, but as you might notice, it rotates the player's y axis towards the mouse, not the gun. I want the gun to point towards the mouse.

        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector3 direction = mousePos - transform.position + new Vector3(0, 0, 10);
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90;

        transform.rotation = Quaternion.RotateTowards(
            transform.rotation, Quaternion.AngleAxis(angle, Vector3.forward).normalized,                     rotationSpeed * Time.deltaTime
        );
#

ok the sprite is much tinier than I expected oops >_> Well, he's holding the gun to the right of his head

teal viper
#

The simplest solution would be to fix the sprite to point up or right.

queen adder
#

I'm currently trying to update the object texture but it's not working for some reason

ivory bobcat
queen adder
#

SetTexture work for 3d Meshes and Sprite.Create work for 2d sprites

tender vessel
#

i need help with something

tender vessel
summer stump
#

Can't help without knowing what you need help with. But we would be happy to

prime horizon
#

Guys, I'm building a character movement script for my 2D platform game. I got this code right here. I attached this script to my character, and the variable isGrounded always true. How can I fix it?

using System.Collections;
using System.Collections.Generic;
using System.IO;
using Unity.VisualScripting;
using UnityEngine;

public class Charater_Moving : MonoBehaviour
{
    private Rigidbody2D player; //Get the Charater Rigidbody for movement
    //Moving
    public float moveSpeed = 5f;
    public float jumpForce = 5f;
    //Jumping
    public Transform groundCheck;
    public LayerMask groundLayer;
    public float groundCheckRadius = 0.2f;
    private bool isGrounded;
    private int extraJumps;
    public int extraJumpsValue = 1;

    private void Start()
    {
        player = GetComponent<Rigidbody2D>();
        extraJumps = extraJumpsValue;
    }

    private void Update()
    {
        // Handle left/right movement
        float moveX = Input.GetAxis("Horizontal");
        player.velocity = new Vector2(moveX * moveSpeed, player.velocity.y);

        // Check isGrounded
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
        Debug.Log(isGrounded);

        //Handle Jumping
        if (Input.GetKeyDown(KeyCode.Space) && (isGrounded == true || extraJumps > 0))
        {
            player.velocity = new Vector2(player.velocity.x, jumpForce);
            if(isGrounded == false) extraJumps--;
        }
    }

}
summer stump
prime horizon
summer stump
queen adder
summer stump
summer stump
prime horizon
queen adder
summer stump
prime horizon
#

ok

summer stump
prime horizon
#

This is the inspector with the script stuff

summer stump
#

Ground check is not moving with the player

#

And stays on the ground

queen adder
#

you should move the rigidbody2d and character_moving from "Captain [Demo]" to captain

summer stump
#

Thus you can jump infinitely

#

Well, at LEAST move the rigidbody. But far more crucially, move the "Character_Moving" to Captain

#

That is the script actually moving

woven crater
#

why when i drag the game object disapear in the game tab but in scene tab its still visible and moved

#

oh wait wrong code

silk night
#

Just out of view or invisible?

queen adder
agile oriole
silk night
ivory bobcat
#

Check out the objects position. Likely it's at the camera position (Z)

teal viper
ivory bobcat
#

Which might be at -10

queen adder
woven crater
#

ah i see now its out of camera z position

amber spruce
#

how do i like activate a animatoroverride

ivory bobcat
#

Maybe just do cs var mousePos = ... mousePos.z = 0; transform.position = mousePos;

prime horizon
#

@summer stump @queen adder I just deleted Rigidbody2D and Charater_Moving Component from the Captain[Demo] and added them again to Captain, but the problem still exits

gritty roost
#

what’s the shaders

#

i need shaders

queen adder
#

delete everything and then add an empty gameobject, add your moving script and a rigidbody2d to it
add a square object as a child to it and add a boxcollider2d to it
add another empty gameobject and this should be your groundcheck

summer stump
prime horizon
#

that means the charater will have 2 child: groundCheck and FallDetector, right?

summer stump
teal viper
boreal tangle
#

does someone have a good reference for 2d player movement in unity

summer stump
queen adder
boreal tangle
#

ok ty

prime horizon
#

The White square belongs to the "Player" or the "Square"?

queen adder
#

discord is missing with me

deft quarry
#

How would I make a script for a 3d game thats supposed to move the camera and follow my player using Time.deltatime?

summer stump
gritty roost
summer stump
gritty roost
#

yes

#

i need shaders

summer stump
# gritty roost i need shaders

Ok... tell us more though. Because that is super vague. All games use many kinds of shaders.

All I can say is look on the asset store or google it 🤷‍♂️

prime horizon
#

Guys, it still doesn't work. I hope I didn't miss something.

teal viper
gritty roost
summer stump
queen adder
queen adder
queen adder
prime horizon
queen adder
#

it's in the right place, select player and also screenshot

prime horizon
queen adder
#

yeah, i think it's not the player's issue anymore

prime horizon
queen adder
#

then what's the issue? infinite jump?

prime horizon
#

The isGrounded variable is always true -> infinite jump

rich adder
queen adder
rich adder
summer stump
rich adder
#

yeah weird why does ground have box collider ?

#

tilemap collider already takes care of that

#

anyway outta print the results of what ur hitting just in case

summer stump
#

Is that box collider (assuming that is what Moe pointed out) a trigger? The check will still register a hit on that afaik

queen adder
rich adder
#

i always use this one when workng with 2D
public static int OverlapCircle(Vector2 point, float radius, ContactFilter2D contactFilter, Collider2D[] results); just so I can print results

prime horizon
#

Got damn it, it's green :)))))

#

it has box collider :)))

#

just disable it and the isGrounded works properly now.

queen adder
#

also, your code is not gonna double jump

#

remove it and try this one below

#
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Unity.VisualScripting;
using UnityEngine;

public class tt : MonoBehaviour
{
    private Rigidbody2D player; //Get the Charater Rigidbody for movement
    //Moving
    public float moveSpeed = 5f;
    public float jumpForce = 5f;
    //Jumping
    public Transform groundCheck;
    public LayerMask groundLayer;
    public float groundCheckRadius = 0.2f;
    private bool isGrounded;
    private int extraJumps;
    public int extraJumpsValue = 1;

    private void Start()
    {
        player = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        // Handle left/right movement
        float moveX = Input.GetAxis("Horizontal");
        player.velocity = new Vector2(moveX * moveSpeed, player.velocity.y);

        // Check isGrounded
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
        Debug.Log(isGrounded);

        if(isGrounded) extraJumps = extraJumpsValue;

        //Handle Jumping
        if (Input.GetKeyDown(KeyCode.Space) && (isGrounded == true || extraJumps > 0))
        {
            player.velocity = new Vector2(player.velocity.x, jumpForce);
            if (isGrounded == false) extraJumps--;
        }
    }

}```
#

you need to reset the extraJumps when ever you get back on the ground

prime horizon
#

Yeah, it just read the code

#

I added it after that

eternal falconBOT
summer stump
queen adder
#

haha, it's the effort that counts

prime horizon
slender nymph
#

you probably want to start by constraining the Z axis rotation on your rigidbody. beyond that we probably need more info

prime horizon
queen adder
#

Hello.

solemn fractal
#

hey guys how can I save the color of an object when I am saving data using a method like that ```cs
public static void SavePlayer(Player player){

    string path = Application.persistentDataPath + "/player.save";
    PlayerData playerData = new PlayerData(player);
    var savePlayerData = JsonUtility.ToJson(playerData);
    File.WriteAllText(path, savePlayerData); 

}```

queen adder
#

I need some advice regarding my code. Basically I have a text file that had like 4 million words in it I wrote along the years, but that's besides the point. I have a button that displays a random chunk of it, but it sometimes freezes the game or crashes it the first time you press it but not consecutive times. I have the text preloaded, or had it but the problem persisted. (I didn't remove the preloading thingy) I haven't tested it yet but I added a new line of code: chunkSize and set it to 1000 (lines) or something like that.

Will this fix my problem or should I split the text in multiple files?

solemn fractal
# rich adder same way you save PlayerData

my player data now: ```cs
[System.Serializable]
public class PlayerData{

public int coins;
public int movementSpeedSkillLevel;
public int movemenSpeedSkillValue;
public float playerSpeed;

public PlayerData(Player player){
    coins = player.coins;
    movementSpeedSkillLevel = player.movementSpeedSkillLevel;
    movemenSpeedSkillValue = player.movemenSpeedSkillValue;
    playerSpeed = player.PlayerSpeedControl();  
}

}``` its working fine.. but here I would need to fetch information from a specific component in a specific object to fetch the color. I will be able to do that here?

rich adder
#

You technically won't have the same exact object

#

just use the values to the object from this file

solemn fractal
rich adder
#

wdym Gameobject don't have color no?

#

also GameObject is very much not needed, use directly whatever script these objects are

eternal needle
rich adder
#

all my objects that load stuff have an an interface of ILoadData , I have an event that calls all the LoadData types

eternal needle
solemn fractal
rich adder
#

because its not inheritance you can add many interfaces on 1 script

solemn fractal
#

ahh ok yeah I think i remember about it now, had it long ago during a bootcamp.. true. completly forgot about it, will check it out. thank you!

queen adder
rich adder
#

they're are very powerful, yeah def go over them as well. Pretty handy in almost anything but a load save system as well

solemn fractal
queen adder
#

The strange thing is that it's only happening in the built version of the game but not in the editor.

eternal needle
rich adder
#

probably putting all the lines in memory at once lol

#

use async also for long running operations

queen adder
#

Can I post the whole code? Is it allowed?

rich adder
#

yeah use binsite

#

!code

eternal falconBOT
queen adder
rich adder
#

hmm a split?

queen adder
#

Yes, it's formatted like this:

First sentence.

Second sentence.

#

Don't ask why, I messed up the formatting in the file.

rich adder
#

haven't used textasset too much but for files I use StreamReader.ReadLine

#

much more efficent

#

pretty sure textasset can be loaded the same no ?

woven crater
#

why my ray not hitting the slot? it have slot tag with collider

queen adder
#

Yes. But I don't think that's the main issue. I'll try looking in the profiler like bawsi said.

woven crater
#

debuged it seem to hit box game object and logit out but not the canvas slot object

rich adder
#

GetRayIntersection is weird

#

is therea a reason ur not using RaycastHit2D

rich adder
#

use EventSystem raycast

woven crater
#

is EventSystem raycast use specificly for ui?

rich adder
#

yeah its literally meant for it

woven crater
#

"insert the more you know meme"

#

thank ya

rich adder
#

you can also just use IPointer interface

woven crater
#

whats that?

rich adder
eager spindle
#

is a scene that is additively loaded running on a different thread from the first scene?

summer stump
rich adder
eager spindle
#

oh dang

rich adder
#

ah im too slow

rocky canyon
rich adder
#

JOBS 🙂

eager spindle
#

jobs D:

#

i thought i could at least run a scene additively on a different thread so that my loading screen doesnt hang

rich adder
#

just use LoadAsync version

rocky canyon
#

i use a little timer at the end with a black fader

eager spindle
#

i need the scene to run on a different thread all the time because when I load my main scene it runs an expensive operation

#

i should probably optimise my code

rich adder
#

async could potentially be sufficient ofc you can always move it to a multi-thread operation if you must

summer stump
eager spindle
#

the process involves instantiating objects which jobs doesnt like

#

but come to think of it i should not instantiate 100,000 game objects

rich adder
#

time to convert to ECS

summer stump
eager spindle
eternal needle
summer stump
#

Ecs or fake a lot of the objects by directly drawing them in the gpu. Do they NEED to be gameobjects?

eager spindle
#

not really I can convert my code to use structs

#

drawing them directly in the gpu should be fine I just need to get tmpro's meshes to work with me

#

if I use the default cube mesh provided by unity is it supported by gpu instancing?

#

oh it does

abstract finch
#

Ive tried many things so I'll ask here, I need to check if a target is facing another. Not if a target is looking at the other objects front. I simply need to check if its at a minimum angle to trigger an attack.

verbal dome
#

What have you tried?

abstract finch
verbal dome
#

Looks correct.

abstract finch
#
            
            float dotProd = Vector3.Dot(dirFromAtoB, transform.forward);```
#

Its getting wierd values ill try to debug and show it

verbal dome
#

That also looks correct

abstract finch
#

Then it goes to 40 for some reason

#

the 40 is when the navmesh agent stops rotating meaning its looking at the target so it no longer needs to rotate

#

the number should be decreasing to 0 right

verbal dome
#

It won't decrease to 0 if you tell it to stop rotating at angle 40

abstract finch
#

right but the way the value is going is odd, the navmesh agent over time rotates toward the target

#

this is 60

#

the last pic (40) is when it officially is fascing the target

verbal dome
#

Don't expect me to know what's going on here. Like who's the transform and who's the target

abstract finch
#

ah the left is the transform and the capsule is the target

#

the cube in the front of the left transform represents the head

#

the rotation is done by navmeshagent by default it rotates towards its destination, in this case the target transform

verbal dome
#

Maybe you want to check the Y angle only?

#

float angle = Mathf.Abs(Vector3.SignedAngle((target.position - transform.position), transform.forward, Vector3.up));

abstract finch
#

yea

#

giving that a shot thanks

#

still the same problem

#

im going to try this in another scene and manually rotate it myself

verbal dome
#

So the problem is that it says 40 angle when it is directly facing towards it (and angle should be ~0)?

#

@abstract finch Try drawing the two directions to debug it

abstract finch
verbal dome
#

There is a reason, you just haven't debugged it to find out

#

Draw the two directions that you pass into angle/signedangle

abstract finch
#

how would I do that?

#

you mean debug to get the values of the signed angle and transform forward?

verbal dome
#

Debug.DrawLine/DrawRay, for example

abstract finch
#

the code works fine in the test scene when i rotate the object myself

#

ok i found out the issue its because the enemy transform is a lower Y level then the target

#

so what I will do is create a new Vector3 with the same y as the target and it should work

verbal dome
abstract finch
#
            signedV3.y = 0;
            float angle = Mathf.Abs(Vector3.SignedAngle(signedV3, transform.forward, Vector3.up));
            Debug.Log(angle);```
verbal dome
abstract finch
#

is the one you provided more versatile?

#

because I plan to have flying enemies as well

eternal needle
abstract finch
#

got it thanks

verbal dome
#

The whole point was to not consider height. If you still want height to affect the angle, you might want to adjust the origins used for the direction (target.position - transform.position)

#

If it's a visibility check or something like that, you can ignore the height when the distance is below a certain threshold

cerulean crypt
#

Is there a quick way of getting an instance of the GameObject a Script is attached to? Currently I'm using a [SerializeField] attribute and then setting it to itself, which seems unnecessary

verbal dome
#

It is a MonoBehaviour property and will always exist because MB's always live on a game object

cerulean crypt
#

Also, follow up

#

Is there any way to like, disable an empty (so the child objects go invis) without preventing event functions from being called?

#

So like, RN, I've grouped some buttons using an empty. They know when to disappear because they have a listener method. However, that listener method gets disabled along with the whole script annoyingly. Is there any way around this?

#

Oh, like disabling the child objects ig...

#

Yup, that works. Cool, thanks for reading my ramblings 😂

topaz mortar
#

lol, how do I set this?
Equipment equipment = FindFirstObjectByType(FindObjectsInactive findObjectsInactive) <Equipment>();

#

I need it to return an inactive object too

eternal needle
topaz mortar
#

yeah I found another way to get equipment 🙂

eternal needle
#

that code looks very off too, why is there 2 sets of ()

#

it should be FunctionName<Type>(params);

verbal dome
#

To answer your question, it would be FindFirstObjectByType<Equipment>(FindObjectsInactive.Include)
But yeah, avoid Find

topaz mortar
#

yeah ik

#

I should really learn how to use singletons

#

but there's so many different ways to implement them

#

does C# have something in between discard (_ = await ...) and await?
I'd like my code to keep running, but I do want to make sure my Task is eventually finished

teal viper
#

Why would you need to discard it then..?

eternal needle
# topaz mortar but there's so many different ways to implement them

there really isnt, you may see different ways online but most of them might be an all encompassing overkill solution or may be related to other fields of work. Some use the Find functions to ensure there is only 1 (and throw an error if theres more), but you can just Debug.LogError in the if statement of my example below. You really dont even need thread safety, because i think async/threading stuff isnt needed in most cases. I dont know any cases where you would want to use it tbh
Simplest way can just be

public class SomeClass : MonoBehaviour
{
    static SomeClass instance;
    public static SomeClass Instance => instance;

    void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);
            return;
        }
        instance = this;
    }
}
#

there is also a way to write it with generic classes, but its more so you dont write repeated code instead of actually needing a base class.

topaz mortar
#

cool thx

#

time to refactor my entire code lol 🙂

ivory bobcat
#

What're you refactoring?

topaz mortar
#

making my character a singleton

ivory bobcat
#

Should there only be one?

topaz mortar
#

yup

#

been wanting to do that for a while, but it just seemed too complicated

ivory bobcat
#

Ensuring that ease of access isn't the sole reason to doing so

topaz mortar
#

there's only one, it's in the scene and never destroyed/created

#

and I need to access it everywhere

teal viper
#

Making the player a singleton doesn't sound like a great idea regardless of the circumstances. Maybe make it a property of a singleton game manager.

topaz mortar
#

should be totally fine for my concept, it's not a game where you run around and do stuff

ivory bobcat
#

Usually the purpose of a Singleton is to prohibit the use of multiple instances of the object. They make good patterns for managers that observe other data. They're not a good pattern for use with objects that actually may need multiple instances - quite annoying to undo all of the constraints and dependencies of the ease-of-access instance field/property.

#

And changing the Singleton can have annoying after affects upon other classes

eternal needle
#

Something is going to have to spawn your player, so whatever spawns it can pass it to a singleton game manager easily. If your player already exists in scene, its simple, drag it in the inspector to the game manager

topaz mortar
eternal needle
# topaz mortar but here you told me to just use a singleton?

and the game manager being a singleton is still relevant, you havent really described what this is for so I cant recommend the entire best practices based off 1 line of code. I did find it weird that this was being done on a script called Equipment initially, but i cant really assume what its for

topaz mortar
#

so I should have a gamemanager that is a singleton
to hold a reference to classes like character (which has equipment) to make it easily accessible?

eternal needle
#

a game manager makes more sense to be a singleton, because you wouldnt want multiple instances fighting over stuff. I cant really suggest much because i dont know what needs access to the player

woven crater
#

so i put my item gameobject in the event trigger. the item is a physical object in the scene right now . can i still be able put an instance of the item game object in here in the future??

woven crater
#

well for testing right now the item game object is in the scene im gonna start to instantiate the this item game object in the future, my question if i can still be able to use the event trigger component?

topaz mortar
#

if you make it a prefab and instantiate the prefab then the new gameobject should have the triggers too yes

woven crater
#

you mean i can just put the prefab in the event trigger component and it will work for the instance of the prefab?

#

ah thank you

topaz mortar
#

eh no

#

well depends, it might work in your usecase
don't really know what ur trying to do

teal viper
#

An event assigned in the inspector would always invoke with the parameter you set in inspector.

woven crater
#

ah i see

fringe plover
#

Fixed

blazing estuary
#

Ok

stray wraith
#

Anyone here know how to make DOTween LookAt only change the Z rotation of an object?

minor roost
#

how could i make it work with arrow keys aswell

#

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

public class Block : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    if(Input.GetKeyDown(KeyCode.A))
    {
        transform.position += new Vector3(-1, 0, 0);   
    }
    else if(Input.GetKeyDown(KeyCode.D))
    {
        transform.position += new Vector3(1, 0, 0);   
    }
}

}***

stray wraith
modest dust
#

||

stray wraith
#

|| sorry

eternal falconBOT
minor roost
hidden sun
#

Hi, does anyone know why i can't access a bool variable from another object?

#

I initialized it in 2 objects but i can access only from an object which has the same prefab

#

it needs to be public, but i can't understand why its working without public in planescript

static cedar
#

Ah.

#

public means it can be accessed anywhere.
If you just leave it blank int some_class_var; it's implicitly private.

#

And when it's private, only the type itself can access it.

#

I'd prefer if you take a screenshot of the error code too.

ruby python
#

!code

eternal falconBOT
neon ivy
#

I watched a GDC vid that was about an alternative way in handling quests where a quest is described in multiple states of statemachines in the game, the example given was the state of a commoner if they asked you to kill a wolf, getting impatient and being gone (going to solve it themselves) and the state of a wolf in the woods, if you've heard of it, if you've seen it and if you've killed it.

I'm thinking of a dynamic way of implementing this where the player has a list of states with an ID as to what state machine it belongs to and characters, monsters, places, etc. have those state machines and add to the list as soon as the player has exited the null state. I'm not sure how to implement this though.
I thought of using a list of enums for the state machine but that's not dynamic at all. what is the best way to handle this?

ruby python
#

Mornin' all, I'm having a really weird issue that I can't figure out and it's bugging me. lol.

I'm cycling through a list of objects and for each object I need to find/assign it's parent.
But I keep getting the good old 'Object reference not set' error and I can't figure out why it's not finding the parent of my object.

The debug reports correctly, but it craps out when doing the assigning (ie, doesn't know what 'doorChecker.transform.parent.gameObject' is

    Debug.Log("Number of Door Checkers = " + doorCheckers.Length);
    foreach (GameObject doorChecker in doorCheckers)
    {
    GameObject doorRootObject = doorChecker.transform.parent.gameObject;

Highlighted object in the hierarchy is what is assigned to 'doorChecker'

static cedar
#

You mean doorChecker.transform.parent.gameObject is null or the property somehow doesn't exists according to the compiler?

static cedar
neon ivy
#

a what now? xD

languid spire
#

or you have null entries in the array

static cedar
# neon ivy a what now? xD

It relies on something called abstraction.

public abstract class BaseState 
{
  public abstract void MethodToUpdate();
}

public class StateOne : BaseState
{
  public override void MethodToUpdate() { }
}

public class StateTwo : BaseState
{
  public override void MethodToUpdate() { }
}

These types can be considered BaseState and when you try to call their MethodToUpdate it depends on the actual type of the object.
If the value is a StateOne, it calls the MethodToUpdate from that. And so on.

public sealed class StateManager
{
  private BaseState base_state;

  public void CallTheUpdate() => base_state.MethodToUpdate();

  public void ChangeState(BaseState new_state)
  {
    base_state = new_state;
  }
}

And then you would traditionally have some state manager that all states need to hold, just put it in the constructor of the BaseState so all classes that inherit it(see the : part then the BaseState, the type will hold everything the BaseState has) will automatically have it.

This way, each state object represents a state of it. Better than chaining tons of if or switch cases.

#

If you still can't understand this, i'd suggest you to watch a video about polymorphism or abstract.

static cedar
ruby python
#

This is so weird. I removed that line temporarily and added debugs/object renaming....

foreach (GameObject doorChecker in doorCheckers)
{
 Debug.Log("I am a door checker");
 doorChecker.name = "ThisIsWhoseParentImTryingToFindAndMyParentIs";

This works fine, but as soon as I add the line to find the objects parent, it craps out (even adding it to the end of the rename (hence the 'And my parent is).

languid spire
#

why do you not just debug the data, then you would know. what you have done is pointless because you know no more now than you did

ruby python
#

Not sure what you mean, sorry.

languid spire
#

if (doorChecker.transform.parent == null) Debug.Log(doorChecker.name + " has no parent");

ruby python
#

Ah okay, thank you.

woven crater
#

how to make a game object when dragging know its on a ui and when release mouse it snap into said UI element

languid spire
ruby python
#

huh, okay, so it's the addition of .gameObject to the end of the line. Which is weird, cause that is what everything I've seen/read says that's what to do. lol.

delicate gate
#

can someone help me idk how to make the player move (idk how to put a script like : if button pressed then move player up)

languid spire
short hazel
neon ivy
ruby python
short hazel
#

You have elements in your list that don't

languid spire
#

you only think it does. Did you add the if check I made? What did it output?