#💻┃code-beginner

1 messages · Page 786 of 1

mystic crypt
#

its not mobile actually

#

its using the mouse

naive pawn
#

i think osteel means they're on mobile

mystic crypt
#

oh oops lol

naive pawn
#

are there specific terms or phrases you don't understand in what osteel said

grand snow
#

You record the mouse position, when the distance goes above some threshold you record the new position and add the point to a line renderer.
When some amount of points have been recorded you can tell how much distance has been covered

mystic crypt
#

well im not familiar with line renderer as a whole

grand snow
#

Line renderers have a list of points and it renders a line between them all
does what it says on the tin

mystic crypt
#

well that didnt really go well, to be honest id be fine with the instantiating thing as long as it's controlled so it doesn't lag like crazy.
my only real issue with it is no matter what i do i cant seem to interpolate the mouse movement, right now the spawned objects spread out like crazy if you move your mouse around, but act as normal if you move your mouse slow. the whole 'elapsed' portion was supposed to fix that, but it only did somewhat as it seems like all the hitboxes register correctly but the sprites still show up as spread out? (ignore the particle and 'sketch' stuff, they're purely visual)

{
    Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    mousePos.z = 0;
    transform.position = mousePos;

    if (Input.GetMouseButton(0) && touching && ended == false)
    {
        elapsed += Time.deltaTime;
        while (elapsed >= timeInterval)
        {
            elapsed -= timeInterval;
            cloner = Instantiate(cloned, mouser.position, mouser.rotation);
            cloner.transform.parent = parent.transform;
            ParticleSystem part = Instantiate(particle, mouser.position, mouser.rotation);
            part.Play();
            pixels.Add(cloner);
            sketch.SetActive(true);
        }
         
    }
#

oh right and ‘touching’ and ‘ended’ are also other parts of the code that dont seem to affect the actual issue here

grand snow
#

Why do you not use mousePos for the Instantiation? what is mouser?

mystic crypt
#

i honestly have no idea this code is a mess lol

grand snow
#

Anyway what i said would work. If you keep track of the last world mouse position and keep checking if the current one is above a certain distance then you add a new point to a line renderer and update the last point.

mystic crypt
#

i tried working with line renderer and its just way too much of a hastle for a problem im not too bothered about

#

its so Weird

grand snow
#

the alternative is to draw pixels on a texture or limit how many objects you can have spawned at once

mystic crypt
#

those arent really my issues

#

the mouse interpolation is what im having the biggest issue with (although i barely understand what this means its just what everyone else says causes the insantiated objects to appear scattered and spread out when you move the mouse too fast)

#

the alternatives already been done and its controlled and they all get deleted before it becomes a problem but it just feels really weird to use since you cant move your mouse like you want to without weird effects

grand snow
#

the mouse position read on a frame will be correct unless YOU are doing something special

mystic crypt
#

well i cant think of anything im doing that would change it

#

its not the mouse position thats the issue though

#

its the instantiating of the objects

#

the mouse position is fine

#

but if you hold down m1 and move your mouse rapidly theyll all spawn super spread out

grand snow
#

well make sure the object origin is good (ensure scene view is using "pivot" mode and not "center") and check if the world position used is the current mouse world pos

mystic crypt
#

again its not the mouse position, i forgot to say but ‘mouser’ is actually just an object that follows the mouse around and thats a perfect 1:1

#

i tried the ‘pivot’ change but that doesnt seem to have affected anything

grand snow
#

something else is wrong then

mystic crypt
#

Maybe the whole elapsed thing is being an issue here but im not sure how to remove it without Update() being an issue unless i use FixedUpdate() instead?

mystic crypt
iron cobalt
#

Waddup gamers.
Trying to figure out how to Instantiate a prefab as child of a parent, while using [ExecuteInEditMode]
goal is (if thats how to do it) to be able to collapse and uncollapse the list of GameObjects in the Hierarchy :=)

naive pawn
#

anyways, ExecuteInEditMode shouldn't have any effect

#

you can just set the parent in Instantiate as you would normally

#

(or parent it afterwards if you're used to that)

iron cobalt
#

Ah so parent doesnt matter wheather you can collapse it or not? I have to not just instantiate, but add the new objects to itself?

wintry quarry
wintry quarry
#

Check the docs for more details

iron cobalt
#

Will do! thx 🙂

signal cove
#

Hello. I'm trying to figure out how to teleport my player (red block) from the top of these blue blocks all the way to the bottom. I've tried using a simple box cast and moving my character slowly through the blue block with a while loop, but as soon as I'm inside the blue block's collider I reappear inside. Is there anyway to just figure out how far away the other side of the blue block is and just appear instantly on that side?

empty rapids
#

Can I use this same code for sword attack? Or does it have to be axe only?

using UnityEngine;

public class Immersion; MonoBehaviour
{
[SerializeField] GameObject footstepSounds;
[SerializeField] GameObject handAxe;
[SerializeField] bool isAttacking;
[SerializeField] bool preventCo;

void Update()
{

    if (Input.GetKey(KeyCode.E))
    {
        isAttacking = true;
    }
    if (isAttacking == true && preventCo == false)
   
    {
        preventCo = true;
        StartCoroutine(AxeAttack());
    }
     else
    { 

        if (Input.GetKey(KeyCode.W))
        { 
            handAxe.GetComponent<Animator>().Play("WalkAxe");
            footstepSounds.SetActive(true);
        }
        if (Input.GetKeyUp(KeyCode.W))
        {
            handAxe.GetComponent<Animator>().Play("IdleAxe");
            footstepSounds.SetActive(false);
        }
    }

}

IEnumerator AxeAttack()
{
    handAxe.GetComponent<Animator>().Play("AxeAttack");
    yield return new WaitForSeconds(0.5f);
    isAttacking = false;
    preventCo = false;
}

}

polar acorn
#

Also,

#

!code

radiant voidBOT
empty rapids
old skiff
#

ienumerator in a nutshell pls

#

ok

tight orchid
#

hi

old skiff
#

hi

naive pawn
old skiff
#

i was just being polite

tight orchid
#

fr

#

dont be a dick chris

slender nymph
#

you guys should actually read the content of that link, then maybe you'll actually understand why it was sent.
also #📖┃code-of-conduct

tight orchid
#

you to stfu

slender nymph
tight orchid
#

stop being a party pooper

slender nymph
tight orchid
#

hes just rage baiting ok

#

nice to know

naive pawn
naive pawn
swift crag
dreamy lance
naive pawn
dreamy lance
#

(first time using the paste bin thing idk if it worked right)

naive pawn
#

you can put multiple files in the same bin for convenience, but this is fine as well

lethal meadow
#

is this for hlsl or just c#

slender nymph
swift crag
naive pawn
swift crag
#
IEnumerator GiveMeInts() {
  yield return 1;
  yield return 2;
  yield return 3;
}

This method lets you iterate over the numbers 1, 2, and 3. It gives you one number each time you ask for a value.

To write a coroutine, you do something really similar:

IEnumerator DoStuff() {
  Debug.Log("Doing stuff first");
  yield return null;
  Debug.Log("Doing stuff second");
  yield return null;
  Debug.Log("Done doing stuff");
}
#

when you run StartCoroutine(DoStuff()), you're telling Unity to ask that iterator method for a new value every frame

#

which means the method runs until it hits a yield, then stops and waits

dreamy lance
sick arrow
#

i am trying to open up visual studio code but it does not open. does anyone know how to fix this

swift crag
#

you can also yield a variety of other things, like yield new WaitForSeconds(1f);, to ask Unity to do something other than waiting one frame

naive pawn
dreamy lance
#

its the only one i realy know how to use

naive pawn
#

yeah, muscle memory is kind of a pain like that, you'll get used to it

dreamy lance
#

oh pascel is just capital the first letter of every word

#

got it

naive pawn
#

python convention still says you should use PascalCase for classes though

swift crag
#

you have:

  • camelCase
  • PascalCase
  • snake_case
  • SHOUTY_CASE
  • kebab-case (illegal in many languages)
#

and don't forget sArCaStIc CaSe

naive pawn
naive pawn
#

there's also Train-Case commonly used with http headers

dreamy lance
verbal dome
#

I found myself using a lot of snake_case recently for maths and complex algorithms awkwardsweat it is just so readable for certain stuff

dreamy lance
#

ngl im jsut follwoing a tutorial im still rapping my head around this

swift crag
#

do I have the perfect method for you!

naive pawn
swift crag
#

you can also use Mathf.MoveTowards for a 1D scenario

naive pawn
#

or Mathf.MoveTowards would also work yeah, that basically does what i said for you

#

(though it'll slow down when reaching the goal, which you might not want, but it might not be noticable anyways)

dreamy lance
#

i wanna go back to ue5 blueprints lmfoa this is all hurting my brain lol

naive pawn
#

that wouldn't help you

#

blueprints just turn words into nodes

#

you still have to choose the right words/nodes

dreamy lance
#

no no it would not but atleast id know waht im doing

swift crag
dreamy lance
#

i have no idea how to c#

naive pawn
#

i wasn't very specific, mb

#

it slows down on the last frame it reaches the goal

swift crag
#

yeah, it'll stop once you reach the target, rather than jittering back and forth

dreamy lance
naive pawn
#

though given that it's being destroyed in this case, that wouldn't matter

dreamy lance
#

not to be a smooth brain but any idea how id write that line of code bcs im super lost

naive pawn
naive pawn
#

see what values it takes and returns

swift crag
#

Every function in the docs comes with example code you can look at

#

(well, many of them do, at least)

dreamy lance
#

ok lol so after some testing the curve works it jsut only works to the right lmfoa

#

this might be above my paygrade butt im gona ask anyway. im using animation curves to determine the path is there a way to make it randomly select a curve instead of always using the same one?

naive pawn
#

the animation curve is irrelevant

#

it's controlling the y position

#

right now your x position is wrong

naive pawn
#

but a more flexible solution would probably be to apply y initial velocity and constant acceleration

dreamy lance
#

lol ill figure that out later (im doing this for a jam) and decided to do somthing stupid hard

#

so if im readin gthis right the.move to needs the speed target and i have no idea waht the max delta means

swift crag
#

you could also multiply the curve value by a random value

swift crag
#

what about this is unclear?

naive pawn
#

so if the value represents a position, maxDelta is the maximum distance it can go

naive pawn
dreamy lance
#

thank you

dreamy lance
#

id asume current value is the position in relation to the target?

naive pawn
#

not sure why you're making all those assumptions

#

the current value is the current value

dreamy lance
#

oh waht ?

#

thats my problem i have no idea what value it is recording

naive pawn
#

if you're using it for position, then the "value" is the position, so you can just substitute any "value" with "position"

dreamy lance
#

ok that makes sence... then for the max detla woudlent that just be the target aswell ?

#

bcs the max it could ever go is to the target?

swift crag
#

All it knows is that you gave it:

  • A current value
  • A target value
  • The maximum change allowed
#

It returns a value that's a little closer to the target value

verbal dome
swift crag
#

Importantly, it has no memory of where your object has been

#

Also, calling it does absolutely nothing to your game on its own

#
Mathf.MoveTowards(transform.position.x, 0, Time.deltaTime);
#

This has no effect

#

It calculates a new value that's a bit closer to zero, but it doesn't do anything with the result

#
float x = Mathf.MoveTowards(0, 2, 1);
float y = 0 + 1;

x and y will both have a value of 1

naive pawn
#

for simplicitly, think of the "maxDelta" as just a delta to begin with
that's the amount to move in that specific call

just that when you get really close, moving delta amount might overshoot, so you might move less than delta - that's why it's called maxDelta

dreamy lance
#

ah ok that makes snce

#

sence

swift crag
#

It is an extremely simple function

#

It's easy to try to read too much into it

signal cove
#

Teleporting the player to a valid spot is new to me.

naive pawn
#

i don't think raycasting is exactly what you want. it could work, but it's generally for finding the nearest thing, not the nearest gap

#

you could have an object to represent the valid space i guess, then raycasting would work

verbal dome
signal cove
#

One second then

naive pawn
#

couldn't you use collisions and then teleport the player to the opposite side of the collider? this could be done from either the player's perspective or the blue block's perspective

signal cove
#

I want my player to go from image 1 to image 2

#

But currently it is doing this from image 1 to image 2

signal cove
verbal dome
#

If the blue block is a single object (and you are working with boxes) then what chris said should work

signal cove
#

Alright! I'll try that option then. Mind if I get a bit more detail on what the solution is?

verbal dome
#

You can also use physics queries to confirm that there is free space on the other side to move in
(Not needed if you design the levels so that there's always room on the other side of blue)

signal cove
verbal dome
signal cove
#

Ohhhhhhh

#

I didn't realize I could get that kind of information

#

I'll try it! Thanks!

swift crag
#

and, in general, you can do that by:

  • subtracting the position of the center of the box
  • doing something
  • adding the position of the center of the box
#

in this case, you'd negate the Y or X position after doing that subtraction

signal cove
#

Much better than my method that fails a lot of the time.

naive pawn
signal cove
#

Thank you all! I really appreciate it! Back to work!

signal cove
#

One more question. For my purposes (so I don't get stuck on corners) I used a composite collider on my blue blocks. But now that I'm trying to get the bounds of the individual blue blocks, attempting to do so in scripting gives me the bounds of the composite object which is not the individual collider that I want. Is there a way to get the bounds of the individual items circled in orange? I've attempted a few things like "collider.GetComponentsInChildren<Collider2D>()" but that still gives me the bounds of the overall composite collider.

grand snow
#

you can get the bounds of the sprite renderer

#

or the specific 2d colliders for each square

#

If you get bounds from a composite collider then what did you expect?

signal cove
#

I wanted the benefit of my player not getting stuck on geometry, but now I also want to be able to tell the bounds of the individual blue blocks. I just didn't realize it'd cause a problem until now.

#

I didn't realize the bounds was now a huge square around all blue boxes now.

short hazel
#

I've attempted a few things like "collider.GetComponentsInChildren<Collider2D>()" but that still gives me the bounds of the overall composite collider.
This is normal if you're running this on the object that has the composite collider. Since CompositeCollider2D inherits from Collider2D, it will also be returned, as GetComponentInChildren<T>() searches this object, then its children (yeah this method isn't named properly)*

grand snow
#

If you dont want a player to get stuck then you use different collision shapes for either the map or player

#

a circle for the player usually yields better results vs a box

signal cove
#

Hmmm. Alright. I see more of what's going wrong.

#

I think I found the right method to do what I want to do! Thanks for the tips!

blissful stratus
#

how can i make the player squeeze when moving

solar hill
#

squeeze?

#

like squash and stretch?

#

thats typically done baked into animations

#

sometimes procedurally on more simpler objects

sour palm
#

hay I'm having an issue with the OnTriggerEnter. I have a trigger on both, one is set as Is Trigger and I do have a ridged body.

radiant voidBOT
solar hill
#

start debugging your ontriggerenter, see if its being called first at all

#

if it is whatever you are doing inside of it might not be fully working

sour palm
solar hill
#

please use inline or paste services for code

sour fulcrum
#

have you put a debug log outside of the tag check

solar hill
#

also verify your player has the player tag

#

and ensure it has a rigid body

sour fulcrum
#

(also you don't need to put the word script in the name of the script, it's implied :P)

sour palm
solar hill
#

why is your player a trigger though 🤔

sour fulcrum
#

that can be normal

#

might not be there only collider

sour palm
#

sorry both have a collider.

solar hill
#

this could a duh moment but are you sure the script is on the correct of the 2 game objects?

#

like you didnt put it on your player?

sour palm
#

yes

#

what?

sour fulcrum
solar hill
#

the player or the other thing your player is touching

sour palm
#

it's on the right object.

solar hill
#

since i cannot read minds im assuming the right object here is the ledge

sour palm
#

yes

solar hill
#

try moving the debug line from the if statement first

#

and see if it triggers at all

#

or do like

visual junco
#

!learn

radiant voidBOT
solar hill
#
Debug.Log(other.gameObject.name);
#

above the if statement

swift crag
#

that way, it'll always log something when the method runs, even if it doesn't find the player

sour palm
#

ok I see so it doesn't seam to be triggering in general.

solar hill
#

you enabled "is trigger" on the ledge collider yes?

swift crag
#

Notably: other.gameObject will be the object with the Rigidbody on it, not the object with the collider on it

sour fulcrum
#

youll have to post screenshots of the related objects w/ inspector then

solar hill
#

but the point is still

swift crag
#

so if you have this:

  • Parent <-- Rigidbody
    • Child <-- BoxCollider

you'll find Parent, not Child

#

oh wait, sorry

#

I made an error: I thought this was for a collision, not a trigger

solar hill
swift crag
#

you can ignore this: you're directly given the Collider that was involved in the trigger

solar hill
#

wont it detect it first anyways?

solar hill
#

make sure the collision layers are set up properly

#

oh also this is a big one make sure you can verify in the scene view while the game is running that the colliders are overlapping, sometimes the collider can be disconnected from your character

sour palm
#

Got it thanks.

solar hill
#

so what was it 🤔

#

you got me curious

sour palm
#

I was using the wrong ridged body. lol

twin pivot
#

ray isnt hitting anything and im not sure why

teal viper
#
  1. You're casting mouse pos to world pos, but then trying to use it as a screen pos:
_mousePos = Camera.main.ScreenToWorldPoint(_mouseScreenPos);
            Ray ray = Camera.main.ScreenPointToRay(_mousePos);

Obviously that's not gonna work.

twin pivot
#

oh my god i am stupid

scarlet raptor
#

C# vs C++

teal viper
#

Imperials vs Stormcloaks

twin pivot
teal viper
twin pivot
#

already checked if the method was getting called and it was so it must not be hitting anything

teal viper
#

Well, there's only one condition there, so you don't need to dig deep.

#

The only other possible reason is a runtime exception.

twin pivot
#

does it track for collisions at its starting point?

teal viper
solar hill
twin pivot
teal viper
twin pivot
deft loom
#

Anyone have any recommendations for decent up to date (6.x, ideally 6.3) beginner level tutorials that make a simple FPS style game? Everything I come across that looks decent is out of date 🙁

teal viper
#

There weren't that many changes that should affect you since unity 5. Those that do, are easily fixable.

deft loom
#

One big one thats not easily fixable that comes to mind is the old/new input system lol. I'd like to find something using the new system so I can learn how to use it properly. And I feel like surely if there's something that significant that I'm aware of which has changed, surely there are other somewhat significant changes I'm not aware of

teal viper
#

You can still use the old input system, so I don't think that's related in any way.

deft loom
#

I could still just download unity 5 and use it too, but I don't want to. Hence me asking for an up to date tutorial.

teal viper
#

And if you really want to use the new one, just learn it separately and apply to your project.

deft loom
#

Obviously you can use deprecated systems if you feel like it, I'm looking for a tutorial which doesn't

teal viper
#

It's not deprecated.

deft loom
#

It literally says its not recommended to use the old system if you try to change it in a new project on 6.3

teal viper
#

And you're not ever gonna find a tutorial that 100% meets your needs. The point of the tutorials is to learn from them and apply that knowledge in different contexts.

teal viper
deft loom
#

Okay sure lmao. I appreciate your input.

If anyone else happens to have a simple FPS style game tutorial they'd recommend thats on unity 6.x, I'd really appreciate the suggestion.

bronze fossil
#

Learning stuff separately is better

#

If you don't understand one tutorial about new input system you can always search a new one

#

But you can't do that if you are learning from a full fps game tutorial video

timber tide
#

Unity has templates for FPS/3rd person. I forget if it's in the hub but you can grab it off the asset store otherwise

bronze fossil
#

Oh ye right

floral ledge
#

Dlich is right though. Work with a old input system tutorial. Then if necessary. Watch a new input tutorial and convert any input. Or. The other way round.

A lot of tutorials also have less desirable coding standards but people still follow them. The idea is to put over a way of getting something done. Most are not the best way. But a way for people starting to get it done without blowing their minds and making them learn a whole bunch of other things.

undone wave
#

Is there a way to avoid GetComponent calls when instantiating multiple objects and then initializing them (that is driven by some variable value in the instantiating object/script)?

#

(of course, other than transform and setting its parent)

naive pawn
#

typically you'd want to use the "main" component that you care about in that instantiation

undone wave
#

so like
ExampleScript instantiatedInstance = Instantiate(prefab, ...)?

#

oh, it seems the type for Instantiate is 'Object' and not 'GameObject' as i previously thought

naive pawn
#

and you'd have prefab as ExampleScript as well

#

it also helps prevent from assigning the wrong prefab - it's gotta have that script

#

Instantiate is also generic, it gives the type you put in

sturdy jetty
#

Hello guys I have an issue with my game. The final wave game object spawns in all of these enemies and a "last room" game object. that game object just keeps track of how many enemies are left in the room. When all enemies are dead, the doors should open. The enemy counter decrements accordingly, and the very same mechanism works elsewhere in the level, but for this particular room, I get a nullreferenceexception error regarding the doors. During run time, the door prefabs are assigned in the inspector, so what gives?

#

The "wave" gameobject is meant to be unassigned since that is for summoning additional waves

frail hawk
#

double click on the error message, it will lead you to the section that causes this

trim eagle
#

sorry really new to unity here how could i make it so that a ball will be thrown and land on a transform pose of an object?

willow iron
#

ok so, i gots this class public class Listing : MonoBehaviour { public Produce product; public GameObject screen; } i want to make an array using this class, but apparently Listing[] listing = new Listing[produceHandler.produce.Length - 1]; only creates the class and not the objects inside the class. how would i create the objects inside the class as well?

hot wadi
wide whale
#

what is the best solution in drawing a tree/graph of connected notes at runtime?
as in, say, something like this. as an input you have the layers each node is on and the relations, and then somehow generating lines drawn between those nodes

willow iron
#

for reference, this is the issue i need help with

warped sierra
#

When...Will indie games made in Unity never get into the Game Awards because of Unity's AI?notlikethis

midnight tree
floral ledge
#

so dont use AI?

#

if you use AI generated assets.. you should be fine

#

pretty sure games made in unity have been in the game awards

naive pawn
naive pawn
#

or get instances from somewhere else

#

it seems like you already have some other source of truth

rain rampart
#

Anybody got any good recommendations on guides or anything to learn unity?

naive pawn
#

!learn

radiant voidBOT
rain rampart
#

thank you!

hot wadi
#

U can cache the references of those objects and add them to the array in the Editor or in the code

willow iron
ivory bobcat
old skiff
#

what replaces FindObjectOfType

#

in code

frail hawk
#

a serialized field

old skiff
#

could u give me an example

frail hawk
#

[SerializeField] Type type;

swift crag
#

You can assign references between Unity objects in the inspector

#

this page talks about common situations, like referencing another object in the same scene

sudden adder
#

Anyone else having the issue where its opening a random folder from packages in the inspector after every run?

cosmic dagger
old skiff
#

where is the shadow atlas.

#

Reduced additional punctual light shadows resolution by 2 to make 6 shadow maps fit in the 2048x2048 shadow atlas. To avoid this, increase shadow atlas size, decrease big shadow resolutions, or reduce the number of shadow maps active in the same frame
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&) i got this error

jovial forge
#

Taking a quiz on Unity Learn, says my answer is incorrect. The only thing to me that seems wrong about my answer is "text" and not "string". However, everything else seems correct. What am I missing?

grand snow
#

unity formats our var names into nice readable names for us:
playerName -> Player Name

jovial forge
grand snow
sterile coral
#

yo i am watching a tutorial because im learning but when i made the script it didn't work and i dont know why can someone help?

grand snow
#

Go to player settings > other to find the option to change what input system is used by unity.

hot wadi
#

How old is that tutorial?

sterile coral
#

pretty old

#

5 years

#

but in the tutorial he uses a version from 2019 but he explains it really good

hexed terrace
#

It's still a valid tutorial, you're just gonna run in to things like this that have changed over the versions

sterile coral
hot wadi
#

It’s ok but most of them are pretty niche. U should take a look at the pinned messages for learning sources

old skiff
#

can someone pls answer my question

hexed terrace
#

what question

old skiff
#

where is the shadow atlas

hexed terrace
#

They're in the RP settings file. That's a non-code question and this is a code channel. Delete and ask in #💻┃unity-talk and state which render pipeline you're using so soomeone can give more accurate help

normal mango
#

I'm trying to make a card game sim, but the hand isnt being displayed properly. its supposed to be positioned at the bottom and slightly rotated, but neither are happening, and I'm getting errors I don't understand. Can anyone help?

#

I can show my scripts but I'm unsure which is causing the issue

#

Here's my hand manager

#

So i just closed and opened unity again. The errors are gone, but the cloned objects still wont turn or move despite the transform component having values

dawn wave
#

Weirdly enough I too am messing around with my own card spawning implementation complete with the same cardCount local variable name usage lol. But anyways, we have similar implementations except in my for-loop I iterate through my List of Card-GameObjects and grab their Rect Transforms. I then use rectTransform.localRotation to rotate them. I wouldn't be able to tell you why that works for me but not for your use of "transform.localRotation".

warped sierra
normal mango
#

Maybe it's not a code issue, because even when I move the object around in play mode it doesn't actually move

#

The cards are hard stuck at 0,0,0

#

Not even respective to the parent object

normal mango
dawn wave
#

did you give your cardPrefab prefab asset a Rect Transform and then in UpdateHandVisuals() you did something like "RectTransform rect;" "cardsInHand[i].rect.localRotation = Quaternion.Euler(0,0,X);"

grand snow
#

Ugui layout components don't mess with rotation so perhaps an animator is overriding rotation changes?

normal mango
#

I literally have nothing else in the game yet, just the card prefab with data and hand logic

#

Didn't expect to run into a bug like this

#

Not sure how to even debug, the rect transform component has values but the object won't do anything with them

grand snow
#

That can't be true

normal mango
#

Wait hold on, I think I'm getting somewhere
Realized I was missing a parent canvas over everything, but now they do technically rotate but don't properly display

grand snow
#

Let me guess you are using sprite renderers?

#

In a ugui canvas you need to use components like Image and RawImage

normal mango
#

The prefab is made of Image components... but now I can't see the prefab even in it's own view

#

Is it because of the canvas component inside?

grand snow
#

Check all the children sizes and anchors and fix em up!

#

Yes you do not need a canvas here

normal mango
#

I got it!! For some reason, the prefab components had 0,0,0 scales

#

Thanks everyone!

dawn wave
#

my god we think alike

stark vessel
#

can I make an insepctor variable that points to a method on another script? even if its like the script has to define the open methods that can be called

rich adder
#

what are you trying to do, this can turn into xy issue

stark vessel
#

I want to make a system where I can have interconnecting pieces that do things like buttons and doors

rich adder
#

there's probably several ways you can accomplish this but that depends on many factors, simplest to start is probably UnityEvent I think

#

interfaces would be another way, but you need third party asset / custom inspector to expose them in inspector

stark vessel
#

so I set a unityevent to a function and I can select it from other things

grand snow
#

Kinda, the suggestion here is a unity event would be used somewhere to then add a call to say Open a door

stark vessel
#

ok

rich adder
#

tbh would help if you give us more specifics

grand snow
#

you can still achieve what you want with code and no external assets:

[SerializeField]
MonoBehaviour thing;

void Start()
{
  IOpen openable = (IOpen)thing;
  openable.Open();
}
#

you just have to take extra care with what you assign. You can add edit time verification but thats going a bit far for a beginner

rich adder
#

ah yea I forget MonoBehavior can be used as field lol

grand snow
#

can also be Component but ofc only MonoBehaviour can implement our interfaces

stark vessel
#

So I could make a MonoBehaivor that just does something when it starts and maybe a loop?

#

and then trigger that monobehavior

grand snow
#
public interface IOpen
{
  public void Open();
}

public class Door : MonoBehaviour, IOpen
{
  public void Open()
  {
    //Do shit
  }
}
dawn wave
timber tide
#

Trying out some ideas with Unity 3D, usually I just do my own physics queries for attack hitboxes, but let's say I want to generate a bunch of boxcolliders on my character which I will enable depending on each attack. So we'll be enabling them on and off when used, but the questions I'm looking for:
1#: If the collider is enabled then disabled in a single frame will OnTrigger methods still invoke?
2#: If the collider is completely inside of another collider will it call OnTriggerEnter?

#

Really wish Unity had a collider.Cast method for 3D

cosmic dagger
dawn wave
#

Right, but in his Answer he just writes gameObject.Instantiate(...) in Start() without using the static class name

verbal dome
#

Static methods that appear as member methods of another class

cosmic dagger
dawn wave
#

where i'm confused is that if I do Instantiate() with 3 params, Unity will think I'm trying to use the default Instantiate(object, transform, bool) and not my own defined extension method with three params unless I prefix and do ExtensionMethod.Instantiate(3 args);

#

ExtensionMethod being the static class name

cosmic dagger
teal viper
#

Wouldn't that cause a compile error anyway?

cosmic dagger
#

their custom version, did not have the same parameters, so they did not have that issue . . .

dawn wave
#

is it because in the stackoverflow example, he has 5 args and at most the default Instantiate() has 4 so it's already a unique overload so no confusion on the compiler?

dawn wave
#

I guess I'll make a dummy extended Instantiate with 5 args and see if I can drop the class name to confirm

verbal dome
teal viper
verbal dome
#

Object.Instantiate is a static method so making an extension method (which is called on an instance) with the same name is super confusing

dawn wave
#
public static class CreateCardExtensions
{
    public static GameObject Instantiate(GameObject original, Transform parent, CardAnimationStyle style)
    {
        GameObject card = Object.Instantiate(original, parent);
        ItemCard itemCard = card.GetComponent<ItemCard>();
        itemCard.style = style;

        return card;
    }``` and then in some other class I simply do ```cs 
CreateCardExtensions.Instantiate(prefab, parent, enum);``` My confusion is that in the stackoverflow example, he simply does gameObject.Instantiate(5 args);
#

well i goofed the paste

verbal dome
cosmic dagger
#

you forgot to add this . . .

teal viper
#

Your code is not an extension method, unless you do what Osmal pointed out.

dawn wave
#

Oh.. I have the habit of dropping stuff if I don't understand why it's there. I just looked at Instantiate() documentation and compared the overloads vs the stackoverflow's and didn't understand why it's there

wintry quarry
#

Well now you understand why it's there - it's a fundamental part of writing an extension method

dawn wave
#

yeah, appreciate it everybody

cosmic dagger
#

@timber tide if you want to check for a collider, use a manual physics query instead . . .

timber tide
#

Yeah that's what I was thinking too about the physics frame. I'd have to await till next physics step atleast before disabling it. It's just a pain in the butt to really get an idea of the hitboxes on the editor side

#

Need to add a bunch of debug shapes to see what im doing

cosmic dagger
wise cove
#

Hello, with OnTriggerEnter2D, you can use the argument other to know what collider this object's collider is touching, but can you also know what this object's collider if there are more than one? The script with OnTriggerEnter2D is on an object, and this object has a child object. Both the parent and the child have a collider, so OnTriggerEnter2D on the parent's script is also activating when the child's collider touches the other collider, which I don't want. So just like how we can check the tag of the other collider, is there a way to check the tag of this collider to make sure it's on the parent and not the child?

#

or is this impossible and i'll have to change all my logic?

dawn wave
#

i recall implementing some kind of logic that filtered certain colliders and storing the colliders I specifically want into an array.. I think I used Physics2D.OverlapCircleAll(circlePosition, circleRadius, LayerMasksToCheckFor) which just returns an array of 2D colliders that's within the circle and are of your desired layermask(s)

hot wadi
hearty dagger
#

Why we should check input in Update() instead of FixedUpdate(), if this input is for movement (physics related)? I watched video of some guy and he told that with Update() it would be more precise for games that need high reaction speed, so if it is more fps - it would be earlier action execution. But it is wrong, no? Movement still will be executing in fixed update and so it is would not be faster. So checking input in Update() instead of FixedUpdate() just adds redundant processing of input when it is not needed?

hot wadi
timber tide
#

event input system gets around this though

#

so ya don't really need to poll if you don't want to

hearty dagger
wise cove
# hot wadi Tags or layers are ok. But they can get tedious if there are too many objects. I...

So it's basically an action platformer, kinda like Hollow Knight. The player object (which has its own collider) has many child attack hitboxes (left, right, etc.) each with a trigger collider that will be setactive when the attack button is clicked. the enemy currently has a collider and a child attack hitbox with a trigger collider that's in the same location as the normal collider so that it does contact damage. I did it this way so that i can easily edit the enemy to make different types of enemies like walkers. all child attack hitboxes have tags (player attack hitbox or enemy attack hitbox). I have a script on the player so that when its main collider (the collider on the parent) touches an enemy attack collider trigger (checked using other.CompareTag), i can decrease health and all that. Same with the enemy, i have a script so that when its main collider touches a player attack collider trigger, i can decrease the enemy's health. I tried to do this with OnTriggerEnter2D but when the player attacks the enemy, because the player attack collider trigger is touching the enemy attack collider trigger, the player's OnTriggerEnter2D activates even though its child's collider trigger is touching the enemy attack collider trigger. this is why i want to be able to check exactly which player collider (parent's collider or child's attack collider trigger) is touching the enemy attack collider trigger.

#

sorry for the long message

hot wadi
hearty dagger
#

okay, thx

dawn wave
#

@wise cove Every one of you hitbox circles has some kind of Collider2D component. Whether it be CapsuleCollider2D, CircleCollider2D, BoxCollider2D... Physics2D.OverLapCircleAll will store it into a Collider2D array. Give your player and enemy script each a unique LayerMask variable. And then for OverLapCircleAll pass (positionOfHitBox, radiusOfHitbox, LayerMaskThatIsPossibleToHurt). And then iterate through the Collider2D array, Get'ing the relevant script component so it'd be something like detectedDamageableCollidersFound[i].GetComponent<MyDamageManagerScript>(); and then call the function that'll apply damage. That's my noob approach anyway..

wise cove
#

that's the idea that would take a long time

#

i guess i better get to work

#

thanks anyway

#

wait can you do this with ontriggerenter2d

dawn wave
#

i don't think i've used ontriggerenter2d other than for simple stuff or quick and dirty testing because from my perspective it doesn't give a lot of control?

#

well to put it better it's a nice and easy way to do a check

sour palm
#

I just want to ask.
I have a script for a object with an OntriggerEnter that checks if a player is in the trigger. It works fine but now I need to call that part in my PlayerScript. So that my PlayerScript knows that since it is in this trigger it can preform an action.

how would I do something like this. I've tried a few things but I just haven't gotten it yet.

hot wadi
#

Make sure to check if it's null

#

Or u know, if the Player object has its own collider, just call the trigger event inside it

sour palm
wise cove
sour palm
#

would this then be something I would call in the PlayerScript script?

hot wadi
sour palm
dawn wave
#

@wise cove look into Gizmos.DrawSphere/Line as well because the shapes you use to check for colliders for don't appear in Scene or Game view.

wise cove
#

also basically what i do is move all the trigger/collider check logic from the one getting hurt (parent) to the one hurting (child), correct?

dawn wave
#

I'd imagine you'd want to generalize it. Check for specific layermasks within the collider and if found, call your damage function on it.

rocky whale
#

is the point of a singleton to make sure certain objects live forever from awake till the end unless you specifically kill them ?

runic lance
thorn ginkgo
#

I'm following a tutorial on Youtube. The tutorial is using OdinSerializer, which I found on the asset store for about $37. Before I spend money on an asset, I would like to get some feedback on OdinSerializer. Is it a good asset? I see it is used for compressing and decompressing data, useful for save files; I'm sure it has other uses too. If it is a good asset, then OdinSerializer will be useful for many future projects.

grand dome
#

!code

radiant voidBOT
upbeat olive
#

hi everyone, im trying to upload apk for internal testing on google play, but apk has like 300mb, so i need to split base and assets somehow, i tried by adding .androidpack with buildgradle inside set on install-time. the path for videos within androidpack is src/main/assets/videos, im trying to access files within code by targeting path for example videos/1.mp4, but assets never load on mobile. also another question is there anyway to test these within editor, without building aab, then putting it on internal testing, installing and then testing. like what's the best way to upload 200+ games on gp. i heard about google play adressables that came in 2023, but apk becomes unstable in unity versions above 2022, as current unity version im using is 2022.3.39f1, what's the best method for that unity version? any help would be highly appreciated

grand snow
upbeat olive
grand dome
#

Hello every on I am fairly new to Netcode For Gameobjects and I have a problem with spawnning the Gameobjects can someone have a look into it here's my code
https://paste.mod.gg/
I simply spawn in the Spawnner class and when the cards are spawn the OnNetworkSpawn method on the BaseCards should execute which in turn should call the AddCards method on the CardsHandView class and add the cards to the cardsInHandList but it only works for the client and not for the host when only one client is connected

twin pivot
#
  click = gameObjects._playerInput.actions["Click"];

i'm getting a null reference from this line and im not sure why that is

grand snow
glass summit
#

does anyone know what this means?

frosty hound
#

Yes but the context matters. Show your code.

hearty dagger
#

Are rigidbody.linearVelocity = targetVelocity and rigidbody.AddForce(targetVelocity - rigidbody.linearVelocity, ForceMode2D.Impulse) the same thing?

wintry quarry
#

(aside from floating point error)

#

Oh 2D doesn't have VelocityChange

hearty dagger
#

yeah

wintry quarry
#

So you'd have to also multiply by rb.mass

#

(target - current) * mass

hearty dagger
#

So actually I don't need to use addforce if i can just do rigidbody.linearVelocity = targetVelocity? But docs saying "The value is not usually set directly but rather by using forces.". So what should I do, use addforce or just change velocity?

grand snow
naive pawn
#

keep in mind that that would make it disregard any other forces though

stone oar
#

hey there, got a question but not sure where i should put it since im new here: I'm using an automesh script, here it is -

    {
        NavMeshSurface surface = GetComponent<NavMeshSurface>();
        surface.BuildNavMesh();
        
    }```

that basically gets attached to a prefab of a room and runs the navmesh building function, but the issue is that **ProBuilder **meshes are not being touched like at all. they're just ignored, unless i manually run the navmesh builder in inspector, which i cant because prefabs don't store navmesh data.

maybe there is a better way to do what I want to do, which is to randomly spawn rooms that player has to go in using prefabs (that way i don't have a thousand objects in the scene at the same time).

never the mind, turns out I just needed to put it on `Start` instead of `Awake`
still ingot
#

I swear I don't know why I am just starting to figure out and really like using scriptable objects this is really life changing to how i develop my projects now.

#

Working on a 2D rail grind system

solar hill
still ingot
#

There are times where my scriptable object doesn't save the data i input even after saving

still ingot
solar hill
#

by input you mean set up in the inspector?

still ingot
naive pawn
#

are you doing any OnValidate stuff

still ingot
#

No, I have been saving regularly too. So I may just try restarting my computer and reopening my project

#

Okay my project is saving now I ran into a new issue which is the magnitude of a rigidbody 2D player. How would I set it to a specific value because I am thrown an error when doing so.

#

            if(Mathf.Abs(player.rigidbody2D.linearVelocity.magnitude) > 4)
            {
                player.rigidbody2D.linearVelocity.magnitude = 0f;
            }```
naive pawn
#

what's the error

#

read the error message. it should tell you plenty

keen dew
#

Setting the velocity to zero is player.rigidbody2D.linearVelocity = Vector2.zero;

twin pivot
still ingot
#
        {
            //Sets direction of player
            var player_Input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
            player.setDirection(player_Input);

            //Flip sprite facing
            PlayerDirectionalChange();

            //Movement
            var movement = player_Input * player.MoveSpeed * player.MoveSpeedMultiplier;
            player.rigidbody2D.AddForce(movement * Vector2.right);

            //Clamping magnitude
            Vector2.ClampMagnitude(movement, player.MoveSpeed);
        }```
#

I tried adding Vector2.ClampMagnitude to help prevent it from going above the movespeed I created but still run into the same issue.

keen dew
#

Clamping the movement variable doesn't make sense, and you have to assign the return value of ClampMagnitude to something

#

Try player.rigidbody2D.linearVelocity = Vector2.ClampMagnitude(player.rigidbody2D.linearVelocity, player.MoveSpeed);

warm sequoia
#

Is this possible with realtime lighting in HDRP?

#

The problem is that currently, I need to allow players to import their maps from a file, so I generate everything on runtime, but can I in somehow bake the light or something before the player switch to the scene?

solar hill
#

i guess with real time gi?

#

you could do it

warm sequoia
#

And for the lights in the ceiling what should I use for type of light? (ex: Spot, Point, Directinal)

#

I have a currently a lot of flicker from the lights

remote spade
#

how do i change the sprite renderer trough script

naive pawn
#

you generally don't, you change the sprite inside

#

you would get the sprite renderer and then assign to its sprite property

void dawn
#

how do i make a loading screen that appears when a scene is being loaded ?

i need a system that makes so that when a scene is being loaded it shows a loading screen , just so the game looks more professional , but i don't know how to do it , can anyone tell me how ?

polar acorn
swift crag
#

Light baking takes a long time to get good results

#

note that "realtime GI" is also baked in advance: it just computes the actual illumination at runtime

#

(it pre-computes which surfaces can see which other surfaces)

#

Raytraced GI may be able to help here, but I'd still expect to have problems

verbal dome
#

HDRP also has SSGI which might help, but that alone won't do it

swift crag
#

That too, yeah.

eager needle
#

Hello guys, I hope everyone is doing fine here. I am trying to make a very simple platformer with chicken as a hero for my daughter. I am struggling with a concept.. I have a player and as child a spawn point. I am trying to make a projectile spawn there AND have like a specific rotation. I got that rotation on the spawnpoint and using instantiate(prefab,spawnpoint.position,spawnpoint.rotation hoping that it will get the rotation from the spawnpoint. unfortunately. it's going straight with a global vector2.right. I don't get it. could someone help me to understand why? and how to fix it?

swift crag
#

how do you make the projectile move?

eager needle
#

on a side note, my projectile is a rigidibody2d with gravity enabled.

swift crag
#

If you apply a force to the rigidbody without considering the rotation of the projectile, it'll always move in the same direction

eager needle
#

I am adding force.

eager needle
#
             GameObject egg = Instantiate(eggProjectile,spawn.transform.position,spawn.transform.localRotation) ;
             egg.GetComponent<Rigidbody2D>().AddForce(Vector2.right * 10,ForceMode2D.Impulse);
swift crag
#

You can either do this:

rb2d.AddForce(transform.rotation * Vector2.right);

or

rb2d.AddRelativeForce(Vector2.right);
#

AddRelativeForce uses a local-space direction

eager needle
#

let me try that right away.

swift crag
#

The first option rotates the vector (which is then interpreted as a world-space direction)

#

you can use * to combine a rotation with a vector

eager needle
#

it worked. it has applied the localrotation

#

Thanks @swift crag

swift crag
#

nice! (:

#

Also, if you're unsure which directions are which, you can look at the Move arrows when you have the object selected

#

make sure the scene view is set to "Local", not "Global"

#

red is right, green is up, blue is forward

eager needle
#

yes I got that. it was more that I did't understand why it keep using the global

#

if I am not abusing. got another question. when my player is spawning the projectile there is a recoil that make my player goes back.

eternal needle
swift crag
#

it doesn't matter which direction the object is facing: you're still pushing the same directino

swift crag
#

But I'm actually unsure about it. The docs say:

Ignoring collisions refers to any type of interaction between the selected Colliders i.e. no collision or trigger interaction will occur. Collision layers are first checked to see the two layers can interact and if not then no interactions take place.

eager needle
#

oh change the layer matrix.

swift crag
#

that makes it sound like it just skips the collision and trigger messages

eager needle
#

ok. thanks for the ideal. will try to move it out of the way first and if not will place them on different layer.

swift crag
#

Layers work well when players can hit enemies and enemies can hit players

#

(but there's no friendly fire)

hot wadi
#

Famous last word before my friend pulls the trigger in a new game

frosty hound
#

That's not how that saying works.

eternal needle
eager needle
#

ok. you know what I just move it slighly and now it doesn't collide anymore and the recoil stopped. all good here.

solar hill
eternal needle
eager needle
#

just done it. still no recoil. I just implemented the code to destroy the ennemy on touch from my projectile but I used DOTween to make the patrol move and it raise an error on the console.nullref.

warm sequoia
sour palm
solar hill
#

you have a bool that checks if there is a player movement component on the other object

#

you need to do something like ```

PlayerMovement pm = other.GetComponent<PlayerMovement>(); ```

#

and then do pm.ledgegrabemovement()

naive pawn
#

you need an instance of PlayerMovement, not the entire class

solar hill
#

imagine this

#

your playermovement class is a blueprint for a house

#

you cant live in a blueprint

#

you cant go to sleep in a blueprint

#

you need to tell your code to build the house from the blueprint first

naive pawn
#

classes are blueprints. if you want to come to my house, giving you the blueprints to my house wouldn't help. i'd need to give you an address of my specific house, that's what an instance of the class is

solar hill
#

wow

#

shameless smh

naive pawn
sour palm
#

I know what a class and what calling it is I'm just confused on the implementation.

#

more on how I'm calling rather than were

naive pawn
#

you need to get an instance of the class

sour palm
#

Yes I just put that in.

naive pawn
naive pawn
sour palm
#

Oh sorry I was just over complicating it in my head.

#

lol

#

thank you for your help.

remote spade
#

its my first time using cs and coding in general any tips in how i can improve my script?

    void Update()
    {
        if (Keyboard.current.leftArrowKey.IsPressed() && Keyboard.current.rightArrowKey.IsPressed())
        {
            spriteRenderer.flipX = false;
            mybody.linearVelocityX = 0;
        }
        else if (Keyboard.current.leftArrowKey.IsPressed())
        {
            spriteRenderer.flipX = true;
            mybody.linearVelocityX = -10;
        }
        else
        {
            if (Keyboard.current.rightArrowKey.IsPressed())
            {
                spriteRenderer.flipX = false;
                mybody.linearVelocityX = 10;
            }
            else
            {
                spriteRenderer.flipX = false;
                mybody.linearVelocityX = 0;
            }
        }




    }
#

it feels wrong to use so many if and else

naive pawn
#

regarding style, note that you already have an if-else tree, but you're using an if/else inside the last else instead of just continuing the tree
having more uniform formatting can help make it easier to reason with, to read, to debug, to tweak

remote spade
naive pawn
solar hill
naive pawn
#

suppose you want to change the speed, you have to make sure to change the value in 2 places, and then recompile

solar hill
#

you can do like speed = 10;

and then do mybody.linearvelocityx = speed;

remote spade
solar hill
#

yes but you dont have to make it public

naive pawn
#

it'd be safer to

  • have a shared variable, so you only have to change it once, and so you have a label
  • in unity, serialize said variable, so you can modify it in the inspector without recompiling. this makes it easy to tweak at runtime as well
solar hill
#

you can make it a serialized field

naive pawn
#

well, public does make it a serialized field, i'm guessing you mean marking the field [SerializeField]

remote spade
naive pawn
# remote spade like public int speed = 10?

btw, consider that something like "speed" could be a non-integer
you could have this as a float to begin with, even if you're only setting it as an int
that can help prevent subtle mistakes like having speed be 5 and then wanting to halve that, and then you get 2 because you did speed / 2 and speed was an int

remote spade
#

yh ik

twin pivot
teal viper
teal viper
#

Try drawing a debug ray to see if it's visually intersecting with the object collider(you can alternate it's color depending on hit/not hit for better clarity).

twin pivot
teal viper
twin pivot
teal viper
#

No. Origin position needs to be in world space.

#

Which seems to be the issue with your raycast as well.

twin pivot
#

ah thanks

twin pivot
teal viper
twin pivot
twin pivot
#

how would I track collisions when changing the transform.position of an object? just adding a negligable amount of force at the end?

sour fulcrum
#

Might need more context

twin pivot
teal viper
undone wave
#

trying to pre-warm an object pool using the default ObjectPool<>, how do I do this?

#

my first thought was to just do

for(int i = 0; i < startingInstanceCount; i++)
{
    BulletLogic newBullet = bulletPool.Get();
    bulletPool.Release(newBullet);
}```
#

but of course this just creates one instance

slender zephyr
#

odd question

#

I was following a tutorial that used the legacy input system, but its mostly unsupported now(unless renabled)

#

how can I turn this into the new code?(and its for clicking an object in 3d space, like a physical button, think of the fnaf button, but in 3d space)

#
public GameObject DoorButton;
void Start()
{
    
}

// Update is called once per frame
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Vector3 mousePosition = Input.mousePosition;

        Ray MyRay = PlayerCamera.ScreenPointToRay(mousePosition);

        RaycastHit raycastHit;

        bool buttonHit = Physics.Raycast(MyRay, out raycastHit);

        if (buttonHit)
        {
            Debug.Log("ButtonClicked");
            raycastHit.transform.gameObject.SetActive(false);
        }```
solar hill
# slender zephyr how can I turn this into the new code?(and its for clicking an object in 3d spac...

In this video I show a really easy setup to get you started with the new input system in Unity.

Intro: (0:00)
Overview: (1:18)
Step One: (1:22)
Step Two: (1:49)
Step Three: (1:57)
Step Four: (5:11)

▶ Play video
slender zephyr
#

thanks

twin pivot
#

or is this a problem with it using physics on ui objects again

teal viper
undone wave
#

i set the default capacity, but it didn't do that

#

apparently someone on the forums did say that it just sets the initial list size and not the instances and i assumed that's what happens

teal viper
teal viper
twin pivot
teal viper
teal viper
twin pivot
twin pivot
teal viper
twin pivot
teal viper
#

Then you absolutely don't need physics here.

#

You can detect overlap via the ui api.

twin pivot
twin pivot
teal viper
teal viper
twin pivot
slender zephyr
#

raycastHit.transform. Can I use this piece of code to disable a different object, like a button opening and closing a door?

#
{
    public Camera PlayerCamera;
    public GameObject DoorButton;
    public GameObject Door;
    public bool IsDoorClosed;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Mouse.current.leftButton.isPressed)
        {
            Vector3 mousePosition = Mouse.current.position.ReadValue();

            Ray MyRay = PlayerCamera.ScreenPointToRay(mousePosition);

            RaycastHit raycastHit;

            bool buttonHit = Physics.Raycast(MyRay, out raycastHit);

            if (buttonHit)
            {
                Debug.Log("ButtonClicked");
                raycastHit.transform.
            }
        }
    }
}``` Unless this code is just inefficient and can be done with just the new input where I can click on the object in 3d space and just close the door
twin pivot
slender zephyr
#

a wuh

#

its in a 3d space

fair shore
#

How to make an ui non button gameobject clickable?

slender nymph
#

it needs some sort of graphic (like an Image component), that needs to be marked as a Raycast Target, then you can either use an EventTrigger component or implement the relevant event system interface on your own component (like IPointerClickHandler)

hearty dagger
#

I'm using isTouching of rigidbody for checking if character on ground. It is working fine with single jump. But the problem is when making multiple jumps. I have variable jumpCount that updates after pressing jump button. And in Update() if isTouching returns true than I make jumpCount = 0. And only for a first fixedUpdate after first jump (with changing velocity) isTouching returns still true and so jumpCount resets to 0. In next FixedUpdates it's return false how it should be. And with that, max amount of jumps performed becomes one more than should be. How to fix this? I can just check jumpCount < maxJumps - 1 instead of jumpCount < maxJumps but it is looking dirty

mild reef
#

im new to using arrays. can anyone suggest a video explaining the basics of arrays, or if yall would know how to go about this code here. just want it to check each object in the array

slender nymph
#

there are beginner c# courses pinned in this channel that cover the absolute basics, like arrays and how to loop through them.
or if you want to continue to use the All extension method, you need to learn some more complex topics like delegates. but for that you need to learn the basics first

ivory bobcat
mild reef
#

obviously clicking on menu ui and shooting isnt a good thing

#

arrays have always looked intimidating to me and I have no idea where to start

ivory bobcat
#

For example, pseudo code cs void ChangeWeapon(Weapon next) { curr.SetActive(false); next.SetActive(true); curr = next; }

mild reef
#

nah thats not what im saying. im saying ive got a menu screen, when its active id like to be able to tell and turn off the guns ability to shoot. because i have different ui, I have to check every ui if its active or not

mild reef
teal viper
#

Usage of . All has nothing to do with arrays.

undone wave
#

i have no idea what these are called, but how do you make one of these yourself? (the function array thing in the inspector which look like events?)

mild reef
undone wave
#

oh ok, thanks!

dawn wave
#

Am I going crazy? I was trying to debug why a private float field intialized to 60f was being set to 0 during play testing. I removed its field initialization and just declared it and then initialized it to 60f in the class constructor. It then properly was set to 60f during play testing. I then deleted the constructor and field initialized it back to 60f and now it's properly set to 60f during play testing

dawn wave
#

nope

teal viper
#

Was it at some point?

slender nymph
#

is/was your inspector in Debug mode?

dawn wave
#

possibly

#

yes it's in debug so i can see it since it's private

teal viper
#

Then it was probably initialized from the serialized data(possibly due to debug inspector as boxfriend mentioned).

slender nymph
#

so it's being serialized

#

debug mode just forces everything that can be serialized to be serialized, that's how it's able to display the values

dawn wave
#

i see, good to know, thanks

undone wave
sour fulcrum
#

There's many alternatives as any kind of approach to visual based scripting at any level has a bunch of angles you can look at but what your proposing doesn't raise any immediate red flags

undone wave
ivory bobcat
#

Have the data store elsewhere that's accessible from wherever it needs to be accessed

undone wave
#

would that also work if the parameters are different per function?

#

(e.g. a 'follow object' function would probably have a gameobject and a few floats (movement speed, etc) while a 'follow specific trajectory' function would probably use a set of 2 animation curves or other relevant methods)

#

or i could store all of them as a subclass of a MovementArgs class and get a free custom inspector to use SerializeReference, i guess

lavish spire
#

When I try to paint cloth constraints for my vrchat avatar the brush just doesn't exist

#

Ignore my ramblings of insanity

#

In some names

#

Wrong channel mb

vale totem
#

Why sometimes the wheel collider component rotates wrong direction creating a weird rotation

nocturne kayak
#

Hello guys , should i use ray cast if i want to create an ui when i can interact with something ?

keen dew
#

What is the "something"?

nocturne kayak
#

like i want to display E

#

on the object

keen dew
#

Raycasting is the usual method, yes

nocturne kayak
keen dew
#

no

nocturne kayak
sour fulcrum
#

raycasts are cheap

#

Once you do more advanced stuff you can doing like 1mil raycasts in less than a second 😇

keen dew
#

In any case don't optimize before even starting, make something that works first

nocturne kayak
real thunder
#

What API to get list of all states in the animator?
I want to just get a list of all hashes automatically at OnValidate

orchid hornet
#

What would be the best way to add a pause menu to my shooter game? Using timescale stops the physics, but I can still turn around and spawn bullets.

sour fulcrum
#

I tend to have some sort of bool on the player like PlayerEnabled or something rather and that is checked before doing anything

#

and you would simply toggle that

orchid hornet
sour fulcrum
#

Generally yeah, Others might chime in with more preferable ideas though not sure

#

Just something kinda simple that's worked for me

orchid hornet
#

I was actually thinking of doing that, but thought it might be bad for some reason

sour fulcrum
#

I think it's a weird one as ideally you would want some magical broad solution to the problem and you would want to avoid kinda "hardcoding" it but at the same time you want fairly fine control in disabling specific stuff when paused

undone wave
#

i don't know if this is a good idea, but personally i just have 'Enable/DisableComponentsWhenPaused' scripts that has a list of monobehaviours

#

which is linked to the pause control using events

sour fulcrum
#

Depends as you might have component disabled as a different state than pausing

undone wave
#

that's true

sour fulcrum
#

eg. unspawned, dead etc.

undone wave
#

so i'm trying to make a bullet hell style game
but the problem is that i have no idea how to "define" a level
the level definition is actually very simple; it's just a collection of "Spawn X enemies that do Y at time Z"

#

the problem is that each batch of enemies has to define an enemy, which defines a bullet spawner, which also defines bullets

#

and that makes it really difficult to manage in the inspector

#

are there any simple and better ways of doing this?

sour fulcrum
#

What's your current solution

undone wave
# sour fulcrum What's your current solution

the level manager has a list of 'enemy spawners' that contain

  • the enemy data
  • the amount of the same enemy to spawn (for spawning in groups)
  • the time at which to spawn this enemy
  • miscellaneous data
#

the 'enemy data' is its own serializable class\

real thunder
#

I would make a scriptable object containing scriptable objects containing scriptable objects...

undone wave
#

which nests like 3 other lists of classes

sour fulcrum
#

Yeah a mix of ScriptableObject's and base c# clases generally is the vibe

#

if your already on that vibe you might need to share more specific info and/or look into custom inspectors and drawers

undone wave
#

hmm alright

sour fulcrum
#

scriptableobjects really do be the tech though

#

just as any amount of inspo this was the fairly primitive setup i had for a tower defense game i made at one point

#

using custom inspector stuff to clean it up and do some calculations for me

undone wave
#

oh

sour fulcrum
#

and then there's just a list of these waves that the game runs through

undone wave
#

this seems very useful actually

#

the horizontal list view

sour fulcrum
#

yeah compact lists like that are so much nicer then a hell list of expandable array entries

undone wave
#

how do you make those?

#

right now my definitions look like this

sour fulcrum
#

That's a bit of a big question 😅

undone wave
#

oh, awesome

#

thanks!

#

one problem i have is, i don't think i'm going to be having a lot (if any) of the same enemy occuring twice

#

maybe i could use scriptableobjects to save bullet data, but anything above that is kind of inefficient
(at least, assuming i use scriptableobjects for saving specific presets)

#

unless you can modify bits of scriptableobjects in the inspector like prefabs, i guess?

sour fulcrum
real thunder
#

alright I am confused and out of options at this point
I got annoyed of getting FSM issues time to time so I made a script assuming it would detect if my FSM and animator are desynced

private void SanityCheckState(string state_to_check)
    {
        if (Application.isEditor && !(animator.GetCurrentAnimatorStateInfo(0).IsName(state_to_check) || animator.GetNextAnimatorStateInfo(0).IsName(state_to_check)))
        {
            Debug.LogWarning("expected to have a state " + state_to_check);
            Debug.LogWarning(animator.GetCurrentAnimatorClipInfo(0).GetHashCode() + " going to " + animator.GetNextAnimatorClipInfo(0).GetHashCode());
        }
    }

I manually made a list of string in format "Base Layer.StateName" + int structs and populated it

protected virtual void OnValidate()
    {
        for (int i = 0; i < names_and_hashes.Length; i++)
        {
            names_and_hashes[i].anim_hash = Animator.StringToHash(names_and_hashes[i].anim_name);
        }
    }

So ugh, I am getting logs with hashes which don't match any state names and I just don't get it

#

oh god dammit, I mixed up StringToHash and GetHashCode again, nevermind

#

and also mixed up GetCurrentAnimatorStateInfo vs GetCurrentAnimatorStateInfo...

fickle cave
#

Hey I know nothing about c# and I only know basic of python. Could you help me out and where to find good places or videos to learn c# and unity

#

Is their a thing like in unreal which has blue print?

radiant voidBOT
frosty hound
#

There's also resources pinned to this channel

fickle cave
#

Alr thanks guys 👍

solar hill
#

While in unreal you really want to leverage both blueprints and c++, in unity you should be doing p much everything in c#

fickle cave
#

Alr thanks

old skiff
#

rb.linearVelocity = new (movevector.x, rb.linearVelocity.y,movevector.z); shouldnt there be new vector 3 there and can it break my code if i dont include it

naive pawn
old skiff
#

ok

rocky whale
#

if theres a variable in a script attached to a certain object,how do I get it to a different script on another object ?

polar acorn
modern meteor
#

guys how do I learn if the unity learn page isn’t working for me

rocky whale
#

is this the right way to make a canvas in another game object not show itself when the scene loads

naive pawn
#

why not just have the canvas inactive to begin with

rocky whale
#

it doesnt work when I load that scene after another

#

the canvas is present in all the other scenes aswell but it needs to be active in those aswell

naive pawn
#

no clue what you mean by that

#

if you want to have it inactive to begin with in a specific scene, have it inactive to begin with in that specific scene

rocky whale
rocky whale
ivory bobcat
#

A Singleton pattern would allow you to launch the scenes without conflict if you're needing to test specific scenes with said canvas without entering from the proper entry point (title screen etc).

naive pawn
#

is the canvas in a shared scene or something?

naive pawn
#

is that not the case

rocky whale
#

it is

naive pawn
#

ok, so just have it inactive in the 4th scene and active in the others?

#

when you load the 4th scene, the gameobject will still exist, it'll just be inactive

rocky whale
#

yea when I try that

naive pawn
#

is there something DDOL here

rocky whale
#

if the canvas is part of a singleton

#

could that be the cause

naive pawn
#

that's quite crucial information

#

yes

#

is it DDOL

rocky whale
#

whats DDOL

#

oh

#

yea

naive pawn
#

DontDestroyOnLoad

#

that's also crucial information

rocky whale
#

oh

ebon tangle
#

im nothing of unity

#

idk anything

naive pawn
#

then yes, your 4th scene's canvas is destroying itself, so you see the active canavs from the 3rd scene

naive pawn
radiant voidBOT
naive pawn
ivory bobcat
naive pawn
#

that's the amount of content, not the length of a course

ebon tangle
naive pawn
#

how's that related to unity

ebon tangle
#

idk

rocky whale
naive pawn
#

no, having it be a singleton is destroying it

#

if it's a singleton, you need to consider that every time you interact with it

naive pawn
#

that code isn't treating it like a singleton, it's treating it like a normal object

#

you need to access the singleton instance, not the instance in the current scene, because that might not be the singleton instance

rocky whale
naive pawn
#

no

#

the code in the ss doesn't work because it's destroyed

#

it's part of the effect, not the cause

ivory bobcat
rocky whale
#

This is the scene im talking abt/scene 4

#

the canvas I need to now show

#

is part of game session

#

which is a singleton

naive pawn
#

cool, so exactly as ive described

rocky whale
#

this is there when the canvas is active

#

I keep game session in the scene because it stores the score (right) and lives (left) from the prev scenes

naive pawn
rocky whale
swift crag
#

a "singleton" is something which you only ever have exactly one copy of

#

oftentimes, you can also access the singleton from anywhere

frail hawk
#

couldn´t say it any better

swift crag
#

I frequently see people make singletons by putting a prefab into every scene

#

and then having the prefab deactivate/destroy itself if another instance already exists

rocky whale
swift crag
#

I'm not a big fan of it, since it means you have all of these extra prefabs that immediately delete themselves

#

But there's no reason it can't work

#

You just need to correctly decide if an instance already exists.

#

so, to make sure I understand your problem

#

you want to have one "Game Session" instance, right?

#

do you need to keep it when you change scenes?

rocky whale
#

Yes

#

it stores the score and lives

#

which need to be constant/carried thru

swift crag
#

I'd expect the course you're following to explain this

#

but, in short, you need to:

  • make sure the first instance survives scene changes
  • make sure the other instances never activate

You can do the first by using DontDestroyOnLoad. It moves an object into a special scene that is never unloaded.

You can do the second by using a static variable to store the singleton instance. Other copies of the prefab will see that an instance already exists and delete themselves

#

Together, that would look like this:

#
public class GameSession : MonoBehaviour {
  public static GameSession instance;

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

}
#

whoops, forgot the static

#

A static field is part of the class itself (the blueprint), rather than of instances of the class (specific objects)

#

Whichever one wakes up first will store itself into the instance field and then move itself to the DontDestroyOnLoad scene

#

Every other instance will just delete itself

#

also, if you're wondering why I used Awake instead of Start, the former runs a little earlier

#

when you enter a scene, everything runs Awake, then, sometime later, everything runs Start

#

so a handy rule of thumb is to have things set themselves up in Awake, and then to look for each other in Start

#

I could safely use GameSession.instance in the Start method of other objects in the scene

rocky whale
#

is this implementation very different ? its the one I was using

swift crag
#

That does the same thing

#

It just requires a FindObjectsByType call instead of storing the singleton in a field

frail hawk
#

how do we know this is a singleton

swift crag
#

everything Invadr has said is consistent with wanting a singleton

rocky whale
slender nymph
#

can FindObjectsByType return an object that is scheduled to be destroyed but hasn't been destroyed yet? because if so, this implementation will definitely break if they accidentally put two of those objects in the same scene

swift crag
#

It tells the function what kind of object to look for

swift crag
rocky whale
swift crag
#

but they're doing it in completely different ways

#

my code is storing a reference to the single instance in a field

#

your code is checking how many instances exist

ivory bobcat
swift crag
slender nymph
#

cool, that's precisely what i assumed would happen. and it's good to know for sure that FindXXX can return something that is scheduled to be (but hasn't yet) destroyed

slender nymph
# rocky whale is this implementation very different ? its the one I was using

so this implementation has definitely been confirmed as flawed in that you could end up with no instances if you accidentally have multiple in the scene to start off with.
the implementation that Fen gave you with the static instance variable won't end up with that issue so it's definitely preferred over this

rocky whale
#

uh so Ive used Fen's implementation and its still not working. Is there a way im supposed to access the canvas that im not doing ?

slender nymph
#

define "not working" here, what specifically is not working

cosmic dagger
#

that's interesting, i've never seen that version of singleton before (using FindObjectsByType) . . .

ivory bobcat
rocky whale
slender nymph
#

Let's say, for the sake of discussion, that I was not here for the beginning of this discussion and am therefore not familiar with what your issue was at the start

rocky whale
slender nymph
#

well yes, i don't know what the issue was so how could i possibly help you if you don't tell me what it was

daring sandal
#

Dm me if you need help for your bills or Christmas gifts

modern meteor
rocky whale
# slender nymph well yes, i don't know what the issue was so how could i possibly help you if yo...

ok so,
I have 4 scenes.3 levels and 1 final screen.
The player accumulates score throughout the 3 levels and also maybe loses lives.
When it finishes the 3rd level or dies I load the final scene to display the remaining lives and the score. I keep the score through the 4 scenes using a singleton. The canvas to display the score during the 3 levels is part of the singleton and I want to make it disappear in the 4th scene but its not working

rocky whale
slender nymph
#

define "its not working"
be specific about what you are doing

rocky whale
slender nymph
#

then switch to using the singleton's instance variable. it's static which means you can access it from anywhere

#

that will also mean you don't need a direct reference to it using the serialized field

rocky whale
#

like is there a keyword or

slender nymph
#

a keyword for what? do you not know how to access a variable?

#

if not, there are beginner c# courses pinned in this channel. start there

naive pawn
#

for code specifically, there are c# resources pinned here

modern meteor
#

I just wanna get good at C# for unity specifically

#

I have no future plans using it for other purposes

naive pawn
#

c# for unity is c#

#

(in general) there's 3 major parts to programming:

  • Language - The syntax, structure, and paradigm of each language
  • Library - The interfaces and utilities that each environment or toolset provides
  • Logic - The algorithms to do work at runtime

Logic is almost completely transferrable between each language and environment, you just have to learn the specific Language and Library that you're using
Language is also shared quite a bit between languages

of course, learning 1 part at a time is easier than learning everything at once, which is why tools like scratch or code.org are popular as coding courses for beginners, especially kids, because it only focuses on the Logic aspect

swift crag
#

I use C# exclusively for Unity

#

There's some stuff I haven't ever learned, like how to write a console application

#

but it's a pretty darn small set of things

hot wadi
#

I would like to notify that the pinned “Beginner scripting” link is expired

naive pawn
mystic crypt
#

Hi, any chance anyone can help me out with this problem I've been having?

dodge = Instantiate(dodgers[rand]);

animator = dodge.GetComponentInChildren<Animator>();

circles.Clear();
circles2.Clear();

ac.am = dodge.GetComponentInChildren<amountScript>();
ac.cl = dodge.GetComponentInChildren<cloning>();

if (animator != null)
{
    if (sd.helditem == "pencil")
    {
        animator.SetBool("pencil", true);
    }
    else if (sd.helditem == "spray")
    {
        animator.SetBool("pencil", false);
        animator.transform.gameObject.transform.Translate(0, 0.2f, 0);
    }
}```
Everytime this code runs, I get an 'Animator is not playing an AnimatorController' error, but when I check the hierarchy for this script It's got the correct animator that *has* an animator controller on it, that has the correct bools and the animations play correctly and everything else related to it. I use code similar to this that also gets the animator in the same way that has the exact same controller and that one works fine, but for some reason this one just refuses to work. Any thoughts?
swift crag
#

Try logging it like this:

#
Debug.Log("Here it is", animator);
mystic crypt
#

ive checked the hierarchy when i pause the game and its the correct animator everytime

swift crag
#

Clicking on the resulting log entry will highlight the animator's object in the hierarchy

mystic crypt
#

yeah

#

its always correct

swift crag
#

i'm unclear what you mean by "check the hierarchy for this script"

#

do you mean that animator is a variable that appears in the inspector?

naive pawn
swift crag
#

that's quite a sequence, yes :p

naive pawn
#

that's just the same as the .transform you had earlier

mystic crypt
#

oopsie

mystic crypt
swift crag
#

Does the animator have a controller assigned before the game starts, or are you assigning one via a script?

naive pawn
#

i'd also recommend serialized fields for animator/ac.am/ac.cl to configure that more directly, so you can be sure which instances are used

swift crag
#

yeah, ideally, the prefab would have a component on it like this:

public class Dodger : MonoBehaviour {
  public Animator animator;
  public AmountScript amountScript;
}
#

etc.

mystic crypt
naive pawn
#

so why are you assigning to them here

mystic crypt
#

because they need to be changed throughout

swift crag
#

they are being pulled from the randomly selected prefab

#

so they cannot be assigned in advance

naive pawn
#

ah, that's a doozy

mystic crypt
#

heres another portion of code that does basically the exact samething and works fine, maybe this is an issue somehow?

{
    if (enemy.tag == "nelward")
    {
        attack = Instantiate(attacks[0], b.transform.position + new Vector3(0, 0.3f, 0), b.transform.rotation);
        attack.SetActive(true);
    }
    else if (enemy.tag == "kitty")
    {
        attack = Instantiate(attacks[1], b.transform.position + new Vector3(0, 0.1f, 0), b.transform.rotation);
        attack.SetActive(true);
    }

    animator = attack.GetComponentInChildren<Animator>();

    if (animator != null)
    {

        if (sd.helditem == "pencil")
        {
            animator.SetBool("pencil", true);
            animator.transform.Translate(0.05f, 1.25f, 0);
        }
        else if (sd.helditem == "spray")
        {
            animator.SetBool("pencil", false);
        }
    }```
swift crag
#

I do not see anything else obviously wrong.

#

One possibility is that it's only sometimes going wrong

#

e.g. the code is running twice

#

and it's blowing up once

mystic crypt
#

its running once and happens every time consistently lol i got no idea

swift crag
#

I'd throw in an extra Debug.Log that tells you that the code is running

swift crag
mystic crypt
#

i can see via the console that its only shooting out one error everytime it runs

swift crag
#

yes, and it's possible that the error you're seeing is not coming from the object you think it is

#

you need to start ruling things out until the problem reveals itself

mystic crypt
#

the functions both only run once, ive checked before for earlier problems

#

i think this may just be unity jank

mystic crypt
#

uhh i dont remember in specific but its been checked

swift crag
#

I'm not asking if you think they only run once, or if you previously checked they only run once

#

you need to check what's happening right now!

#

the classic Sherlock Holmes quote comes to mind:

When you have eliminated the impossible, whatever remains, however improbable, must be the truth

mystic crypt
#

i checked and it only runs once

#

and runs correctly based on the 'sd.helditem' check

naive pawn
#

<@&502884371011731486> scam/spam/advertisement

mystic crypt
#

thanks mr ai dev very much appreciated

mystic crypt
#

each object in 'attack' and 'dodge' has its own object that the animator calls for when i should really just be using one for all of them lol

deft loom
#

Why is it that when I create a new gameobject I can't edit the default material on it? It's just grayed out in the inspector

swift crag
#

Unity has some built-in assets that you cannot modify.

#

the default material is one of them

#

Create a new material asset and plug that in