#💻┃code-beginner

1 messages · Page 348 of 1

faint agate
deft grail
#

where are you doing lerp? i dont see

faint agate
#

I had to delete it cause it wouldn't let me save since I was doing it wrong and there was an error.

#

I am not very good at this, I just need advice

lusty flax
#

i would greatly appreciate some help :]

ivory bobcat
#

Try logging what it overlapped.

#

I'm assuming not working refers to you overlapping more than zero objects.

teal viper
#

You could use a ref keyword to pass value type parameters by reference.
That being said, it is sort of against c# design principles. So maybe think of a different approach. For example passing in a delegate.

undone wave
#

how would one do that

ivory bobcat
#

If you're just in need of a generic coroutine, maybe pass the coroutine a delegate that takes a float (delta time) and let whoever calls it define the implementation with the delegate?

eternal needle
#

One thing is you cant run coroutines in an SO. The script using it will have to run their own

undone wave
#

im having trouble understanding how delegates work and how to implement them

undone wave
#

that's what i'm planning to do for now

ivory bobcat
eternal needle
#

Theres basically no point in using the SO there. You could just make some static method

faint agate
#

i am still very confused

undone wave
#
{
    public static IEnumerator scaleChange_outQuad(ref Vector3 targetProperty, Vector3 targetValue, float animationTime)
    {
        ...
    }```
would this work? (delegates yet to be implemented, i don't know how they work yet, trying to find explanations for them)
ivory bobcat
#

I don't believe iterators can have reference variables.

undone wave
#

oh

eternal needle
#

Yea you cant use ref or out. Honestly you might be trying to do too much with the method, like how often will this really be used that classes cant just implement it themselves?

#

Otherwise youd be looking into recreating what tweening libraries already do

faint agate
#

playerObj.localScale = new Vector3(playerObj.localScale.x, startYScale , playerObj.localScale.z);

Im trying to smooth scale the "startYScale", but thats called in Start and I need it there since it holds the standing position of the entire player

lusty flax
ivory bobcat
lusty flax
# ivory bobcat Define "not working".

basically, the script is supposed to prevent you from placing the objects over each other, but this is not occuring as it is unable to properly check if they overlap. consequently, the objects simply overlap regardless

ivory bobcat
#

Is the model destroyed or child to the building?

lusty flax
#

If the script worked, ideally, the objects that would be succesfully placed would be parented to a "Buildings" empty to house all of the placed objects. Objects that were not successfully placed would simply be Destroyed.
However, as the script does not work, what instead happens is that all models are simply kept in the "buildings" empty

#

would it be easier to do this another way? i find that this might be difficult to implement when adding tilemaps into the mix later on

ivory bobcat
#

So the models weren't destroyed, meaning they were overlapping zero objects.

lusty flax
ivory bobcat
#

Log the actual collider you believe your working with: ```cs
Collider2D collider = model.GetComponent<Collider2D>();
Debug.Log($"Click here once during runtime to see {collider.name} highlighted in the scene", collider);

#

Check if it's the correct collider and at the expected location

lusty flax
#

yep it is the right collider

ivory bobcat
#

If model isn't the correct target (say a prefab instead of an actual object in the scene), you'll likely get unwanted behavior

lusty flax
#

would there be a simpler way of doing this?

#

this seems like it would become complicated with more complex shapes or maybe tilemap colliders

#

i just want to make sure that players can't place objects over others

ivory bobcat
lusty flax
#

those two blue objects are the things

#

the objects

ivory bobcat
#

Do they both have collider2ds?

lusty flax
ivory bobcat
#

Can you show the transform component for each?

#

An image of their bounds in the scene view would be nice as well.

ivory bobcat
#

Are you attempting to evaluate after moving the object?

daring dragon
#

why does my noise code break wnvr the seed is anything but 1 float xCoord = (float)x / (mapSize * zoom) + seed;
float zCoord = (float)z / (mapSize * zoom) + seed;
float noise = Mathf.PerlinNoise(xCoord,zCoord);

teal viper
lusty flax
#

The system works as intended, but I am unable to place objects right next to each other

daring dragon
#

Wait I will send screenshot

lusty flax
daring dragon
#

it should stay like the left side

teal viper
lusty flax
daring dragon
#

i am doing that because it seems to break if the value put into the perlin noise is anything bigger that one or less than 0

teal viper
daring dragon
#

So how do I do it correctly, should I add seed to x and then divide by maximum seed number or something?

teal viper
#

Try it

daring dragon
#

Ok

teal viper
#

Actually, maybe it doesn't have to be in the range of 0-1, but integer inputs would always return the same value iirc.

daring dragon
#

I will check that

#

Ok yeh it doesn’t need to be within that but I’m still getting the weird thing

#

My code is now

#

float xCoord = (float)x + seed / zoom ;
float zCoord = (float)z + seed / zoom;
float noise = Mathf.PerlinNoise(xCoord,zCoord);

teal viper
#

Do you understand the order of arithmetic operations?

daring dragon
#

Pemdas

#

Ok fixed that

#

That was just me being silly

#

I will check if it’s still broken

#

Ok I think it’s still broken I’m just testing with different zooms to make sure it doesn’t just appear that way

#

Oh my god

#

I had my seed being recalculated for every pixel

#

I’m so dumb lol

#

Thank you I fixed it

teal viper
#

That explains it

remote osprey
#

I'm super confused on events

#

Hey everyone, how yall doing?

#

so I have a GameManager Class that handles events like drawing a card to the players hand, for example.

#

But I want to make a card whose effect when being played is drawing a card from the deck to the hand

#

I already have this code ready, but I have no idea how to issue the draw command from the card script to the game manager

#

Any help is greatly appreciated

teal viper
#

So for this to work, you'd need to subscribe to events in reverse order. The game manager would subscribe to events in each hand, which the hands would subscribe to events in currently active cards.

#

You don't have to do it via events btw.

remote osprey
#

Oh , ok

#

I got it!

#

it was actually just making the event on Card object

#

then subscribing the Game Manager to the CardDraw Event on the card Object

#

seems to be working well! 🙂

#

Thank you for your help, Dlich!

timber tide
#

My card game works like: CardUI -> CardUIManager -> CardManager

#

if I were to redo it I'd skimp on the UIManager because even though it's nice to separate the UI logic, the editor makes it easy to kinda bind a lot of stuff directly from the UI to the manager

remote osprey
#

it just a little weird making the card control the game object

#

i feel thats better practice

#

at least it makes me feel more comfortable knowing every interaction between scripts are made through events

#

on other note, i want my draggable object event to acess a specific game object, how would i do that without assigning this script to the object?

eternal falconBOT
teal viper
remote osprey
#

a region that when my object/card is dropped on it, the card's effect is called

#

so i need to know if the mouse is on top of this region

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

public class MouseOver : MonoBehaviour
{
    public bool isMouseOver = false;
    void OnMouseEnter()
    {
        isMouseOver = true;
    }
    void OnMouseExist()
    {
        isMouseOver = false;
    }
}
#

So i created a MouseOver class to update when mouse enters or leaves the region in isMouseOver bool variable

#

I want to access that variable of that specific region

#

this region is a game object

teal viper
remote osprey
#

makes sense

#

so basically, MouseOver event passes a message to GameManager object which then passes that message to the Draggable class

#

i think i rather pass it directly to Draggable

#

tbh i think its best to let the draggable initate the event and then ask the MouseOver if mouse is over the region

#

ok i'm starting to get it

#

so basically, its the same thing iwth the cards

teal viper
remote osprey
#

the main problem is that draggable doesnt know its dragging a card, so this makes me think that the Card should implement its own onDragEnd event

#

separate from Draggable

#

then the OnDragEnd event should ask GameMManager to handle the OnDragEnd event

#

I need to pass some parameters to it, looking into that rn

remote osprey
#

bazinga

#

it works!

#

the event handler just freezes while i'm holding the card

#

it only changes the isOver state after i drop the card

#

could it be because raycaster only detects the first element it hits?

teal viper
remote osprey
#

It's a lot of code for me to post here

summer stump
eternal falconBOT
remote osprey
#

this is probably all the code that is involved

#

the region is a plane and the object being dragged is a Card, which is a right cuboid

#

My Camera is orthogonal and it has a Physics Raycaster

#

So i when I'm dragging the card, it blocks the ray to the region

#

Region in red, card is the red/green/white object

#

card is over the regions

#

and a GameManager object has an Event System in it

#

this is the object hierarchy

#

that should be enough info, i think

thorny prawn
#

can anybody help me
i have use chat gpt for code the code looks right but its not working properly
can someone read it

burnt vapor
#

You should really consider learning to do it yourself. ChatGPT is a tool that can help with small blocks of code and suggestions, but it won't be able to spoonfeed you a whole MonoBehaviour like this

eager spindle
#

understand what you're typing before sending it here 🥱

#

dont be a genAI crutch

#

if you do end up as a software engineer and get sent to an airgapped development environment nobody can save you

#

plus the comments explain what the code does

#

its clear you dont know what you want the code to do for you; when it comes to asking programming questions narrow down what is actually wrong with the code rather than sending us the whole script, nobody got time for that

thorn fiber
#

Hi all, having some trouble with camera rotation in an RTS-style setup (trying to learn-by-doing rather than use Cinemachine). Was able to get a beautiful, smooth Slerp movement by rotating the camera around it's own axis but I want it to rotate around the focal point...

RaycastHit hit;
if (Physics.Raycast(cameraInstance.transform.position, cameraInstance.transform.forward, out hit, Mathf.Infinity, LayerMask.GetMask("Ground")))
{
    // Use the hit point as the rotation point
    rotationAxis = hit.point;
}
// Calculate rotation delta based on mouse movement
rotationMouseDelta = Mouse.current.delta.ReadValue();
// Apply rotation only if isRotating is true
if (isRotating)
{
    // Rotate around the rotation axis in world space
transform.RotateAround(rotationAxis, Vector3.up, rotationMouseDelta.x * Time.deltaTime * rotationSpeed);
}```
Have done some debugging, the if conditions are working and the ray cast is setting the correct point. However, this still rotates the camera around its own y axis. Would appreciate any help!
slender nymph
#

considering the comments are all just describing the obvious, there's no way it isn't

burnt vapor
#

That's what I thought, yeah

thorn fiber
# burnt vapor Is this ChatGPT code?

No, I've asked it questions but I try to ask things like what's the difference between x and y, but I try to avoid asking for code as that wont help me learn it

#

iirc the comment structure here came from a tutorial, which is how I ended up with the slerp rotation around local y. I just kept/modified it as I tried to work out how to change it to a rotateAround.

topaz mortar
#

This is UGS Cloud Save.
How/where can I find information on what this return type is and how I process it?

thorn fiber
#

Oh ffs... I worked it out. I can't find a problem with the code because it's correct! It's in LateUpdate and I wasn't using a return; to break out, so other movement code was borking it.

thorny prawn
# burnt vapor We don't help with ChatGPT code

bro chill i am designer i just need the mechanism that's why i use it
its ok to use Ai for stuff you know and so far its working but prompting and iteration is hard for me
you are saying like Ai itself is more useful than u . i am using it is for fast process only

burnt vapor
#

It's not about "being fast" or "knowing the code". Sharing code in here and expecting us to fix it is one thing, but sharing AI generated code you likely didn't spend more than 5 seconds reading yourself is just lazy

#

And it's not up for discussion. This is a beginner coding channel and we do not help people that resort to AI to develop their game. It never works.

thorny prawn
#

slider 1 works but movement for slider 2 is not working idk the issue
i can read most after debugging and things alredy sorted

#

its beginner friendly channel thay's why i asked

burnt vapor
#

Other than that, not sure. I never used this

stone elk
#

why didn't one of my variables in my list change in the editor when i retyped it in the script?

languid spire
stone elk
#

ok thanks for letting me know

kindred halo
#

I'm trying get the yRotation on update and whenever sliding is true but I can't find a way to store it without using it with Quaternion.

transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
yRotation = transform.localRotation;
if (player.isSliding == false)
{
    RotateBody();
    xRotation = Mathf.Clamp(xRotation, -40f, 90f);
}
else if(player.isSliding == true)
{
    yRotation = Mathf.Clamp(yRotation, -90f, 90f);
    xRotation = Mathf.Clamp(xRotation, -90f, 90f);
    transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0f);
}```
thorny prawn
#

here i am cheking a bool name axisX=true in start()
buttonXY.onClick.AddListener(() => ButtonClicked(buttonXY, true, true, false));

    {
        // Update button states
        UpdateButtonState(clickedButton);

        // Determine which axis to assign based on the clicked button
        axisX = axisA;
        axisY = axisB;
        axisZ = axisC;

        // Update slider states
        if(clickedButton == buttonXY)
        {
            if(slider1 != null)
                slider1.value = lastValueX;
            if (slider2 != null)
                slider2.value = lastValueY;
        }
        else if (clickedButton == buttonYZ)
        {
            if (slider1 != null)
                slider1.value = lastValueY;
            if (slider2 != null)
                slider2.value = lastValueZ;
        }
        else if (clickedButton == buttonZX)
        {
            if (slider1 != null)
                slider1.value = lastValueZ;
            if (slider2 != null)
                slider2.value = lastValueX;
        }
    }```
but in update i am checking for Slider currentSlider = GetCurrentSlider(); which is 
```Slider GetCurrentSlider()
    {
        if (axisX || axisZ)
            return slider1;
        if (axisY)
            return slider2;

        return null;
    }```
so axis X is alredy true in start but its giving null error
#

no active slider found is messag

languid spire
#

axisX is false in Start

thorny prawn
#

no current active button is XY one so its active

astral falcon
#

Does anyone know, what the unity UI button is deriving from as default inspector (editor) script?

#

Nevermind, just found it myself. its ButtonEditor for anyone curious 🙂

languid spire
thorny prawn
#

oh i get it

#

i am not assaigning them but checking them my bad

barren vapor
#

Basicly my game is about driving a car (top-down 2D). This is the simple movement of the car:

// Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(0)) {
            //Car rotation
            Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Vector3 perpendicular = transform.position - mousePos;
            transform.rotation = Quaternion.LookRotation(Vector3.forward, perpendicular);
            //Car movement
            rb.AddForce(gameObject.transform.up * -speed * Time.deltaTime);
        }
        transform.Rotate(0, 0, Input.GetAxis("Horizontal") * -rotationSpeed * Time.deltaTime);
        if (Input.GetKey ("space")) {
            //Car movement
            rb.AddForce(gameObject.transform.up * -speed * Time.deltaTime);
        }
    }```

If enemy cars (which chase your), bump into you, you start rotating around like my car gets a sort of velocity against the side or smt. Then for example turning right is harder as turning left.

Is there a way to fix this?
#

I can fix it by freezing the rotation constraint, but then it doesn't feel natural when enemy cars bump into you.

languid spire
#

to start with you should not be setting the transform and the rigidbody, use one or the other.
Second rigidbody changes should be in FixedUpdate

fluid haven
#

Has anyone ever gotten this error before, or knows how to fix it?

barren vapor
dusky pike
#

I have a really random bug that i dont understand at all...

I have a dictionary which stores all tiles in a 3d game.
If i start the game everything works.

But when i change stuff in the code and recompile the dictionary is always empty

#

Do Dictionaries get cleared after recompile?

languid spire
#

yes, dictionaries are not serialized

ivory bobcat
dusky pike
languid spire
dusky pike
#

Is there any function that gets called after Start?
And after every recompile?

languid spire
burnt vapor
kindred halo
#

transform.Rotate(Vector3.left * mouseY);
transform.Rotate(Vector3.up * mouseX);
can we calculate the rotations of these and add them to a transform once a if statement is false?

hexed terrace
hexed terrace
wide stag
#

Hi guys. I had a error. It says that i has a problem in line number 4 but i dont have anything in this line and he tell me about versioncontrol that dosent exist in my code. Help pls

rotund egret
rotund egret
#

mk

hexed terrace
#

In the cases you can't find a channel that fits the topic of your question, then you use #💻┃unity-talk

languid spire
wide stag
languid spire
# wide stag What did you mean?

if the error is saying Line 4 in your code but Line 4 in your IDE is blank it would tend to suggest that the code that Unity is using is not the same as the code in the IDE

ionic topaz
#

So I'm getting a rigidbody2d player to move on moving platforms (the moving platforms use transform.position to move), like most I've tried parenting the player to the platform, however this broke the player movement, but if the platform's moving code is in fixedUpdate it does work, I'm glad it does however I know moving transform.position in fixed update isn't recommended, does anyone know a better solution or can confirm if what I'm doing is okay?

charred spoke
#

The proper way to do moving platforms is to calculate the velocity of the platform and add it to the players velocity after velocity from input has been calculated

ionic topaz
#

that sadly is not an option for me due to my players movement code

wide stag
ionic topaz
#

My player is using Addforce to move which is alread ytricky to work with moving platforms but the actual movement is: cs float targetSpeed = xInput * moveSpeed; float speedDif = (targetSpeed - rb.velocity.x) * currentAcceleration; rb.AddForce(Vector2.right * speedDif);

#

(sorry that's hard to read)

cosmic dagger
eternal falconBOT
ionic topaz
#

got it thanks!

cosmic dagger
#

nnice, place cs on its own line for highlighting . . .

ionic topaz
#

oops

trail heart
ionic topaz
#

I tried that...

#

Things went badly

cosmic dagger
ionic topaz
#

getting them to sync up correctly just never worked

#

I could get close by hardcoding some multiplier

#

but it was never great

#

OHH

#

I think I see what you mean

#

I'll report back

trail heart
#

You might have to remove the friction between the platform and the character to stop it from physically also moving the character

#

But other than that adding velocity from one source to the current velocity should be exact

#

VelocityChange may be a better way to do it than directly changing velocity but I'm not totally sure what the precise difference is

ionic topaz
#

Okay reporting back, I've just done ``` float targetSpeed = xMovement * moveSpeed;
speedDif = (targetSpeed - rb.velocity.x + platform.velocity.x) * currentAcceleration;
rb.AddForce(Vector2.right * speedDif);

#

this does not work perfectly

#

it's close but the player is still not in sync right

languid spire
#

Im not sure what the problem is here
Player lands on platform
-- Parent Player to Platform
-- RB kinematic = true
-- platform and player moves via transform
Player leaves Platform
-- Unparent Player from Platform
-- RB kinematic = false
-- Player moves via Rigidbody physics

ionic topaz
trail heart
#

That code there is doing something else than simply adding the platform's velocity to the player's velocity

#

You don't have to resolve everything into one AddForce call

#

Try adding player's forces first, then the platform speed with ForceMode.VelocityChange

ionic topaz
ionic topaz
#

I don't believe velocityChange is in 2D

cosmic dagger
#

nope, just force or impulse . . .

ionic topaz
#

I mean I can probably just up acceleration when standing on a platform and it'll work

#

I already change acceleration for when knockback happens

trail heart
#

Another option that comes to mind is to increase the friction of the platform a lot instead, if your player is controlled by forces anyway

#

Assuming the platform is also moving with forces/velocity

#

Also assuming your character isn't circular and rolling around

ionic topaz
#

Players physics material has 0 friction

trail heart
#

Having to assume a lot

ionic topaz
#

lol, sorry for not giving much info

#

I've made the platform now just use rb.velocity = "movement code here"

trail heart
#

You could call Rigidbody2D.MovePosition in FixedUpdate exactly as you might use Transform.Translate in Update

ionic topaz
#

I've done that too before

#

no difference between just setting velocity

#

but I'll do that

trail heart
#

The MovePosition needs to get the change of position of the platform since the last FixedUpdate to work right

#

If even that produces somehow weird results, something else must be going on

ionic topaz
#

moveposition is bad

#

as child will not move with parent

trail heart
#

Maybe the way you're detecting the player to be on a platform is not working preciesly from frame to frame

ionic topaz
#

oh that's currently not an issue

#

for testing sake the player is always moving with the platform no matter what

#

Well I believe I have my solution with acceleration anyway now

#

Much appreaciate the help!

frank zodiac
#

why am i getting a red line

burnt vapor
cosmic dagger
frank zodiac
green ether
#

!Ide

eternal falconBOT
burnt vapor
#

Probably Unity​Engine.​Input​System

frank zodiac
#

i did

green ether
#

Im pretty sure you need to setup your ide correctly, it should automatically add it or at least show you an option to import it

cosmic dagger
frank zodiac
cosmic dagger
#

check that your IDE is properly configured . . .

green ether
#

it should still work if you added it manually though

frank zodiac
frank zodiac
green ether
#
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Interactions;

You probably only need the first one

untold hull
#

Does anyone have a good video/tutorial for a skill system? I’m trying to make it so after every wave I get the option of 3 skills to choose from

ionic topaz
#

While I'm here if someone can explain my code to me like I'm 3 years old that would help: float targetSpeed = xInput * moveSpeed; float speedDif = (targetSpeed - rb.velocity.x) * currentAcceleration; rb.AddForce(Vector2.right * speedDif); now I kinda of get the idea but I'd like to understand it better, my moveSpeed is set to 11.5, and when moving right the addforce seems to cap at 11.5 or -11.5 for moving left and when stopping I go back to 0 velocity as if there was drag even though there isn't any

frank zodiac
#

oh wait i need to install the input system from package manager

green ether
#

highly likely

west sonnet
#

What would be the best way to create an Animal crossing or Undertale style dialogue SFX?

#

Where there is a noise on each letter in the dialog, but each is a different pitch?

#

Part I can't figure out is having each noise a different pitch

cosmic dagger
#

change the pitch every time the noise is meant to play . . .

rich adder
#

use a IEnumerator to iterate each char

cosmic dagger
#

access the audio source playing the noise and change its pitch, i presume randomly . . .

knotty ferry
#

Hello i need help with script i don't know how to create a score script that will update the score text when obstacle get's pushed out of the ground and when obstacle respawn's it should add Score +1

rich adder
# west sonnet What would be the best way to create an Animal crossing or Undertale style dialo...

This video covers how to create dialogue audio similar to in games like Celeste and Animal Crossing using Unity.

It covers creating a versatile system for playing the audio, making the audio predictable for a given line of dialogue, and accounting for different configurations of the audio to support multiple speakers.

Just for fun, I also use ...

▶ Play video
knotty ferry
rich adder
ivory bobcat
#

People will help you fix your script but they'll not likely write it for you. !collab

eternal falconBOT
knotty ferry
fleet onyx
#

hello, is this the right section to ask for help?

willow scroll
cosmic dagger
untold hull
#

If i’m setting up a levelmanager gameobject/script, what’s a general idea of everything that should be going in it? I’m creating a 2d castle defense game. Would it just be anything pertaining to that level that would clear outside of the level? Like stat increases/skills gained/monster stat changes throughout waves?

rich adder
#

generally, why would you have stats in a level manager though?

untold hull
#

I’m just wondering generally what a Levelmanager is used for, i’ve seen it in a couple tutorials just unsure of it’s use. I meant more so stat increases, like upon wave completion give +10 attack or something that only pertains to that level, or would those just still stay in their respective game objects

rich adder
#

I would not check manually each level through a manager

#

I would just use the manager to store the array of my Level objects and that is what contains things like maybe Reward obj that can be stat increase, new weapon etc.

#

Scriptable Objects would probably be very handy here

untold hull
#

Gotcha, I think. I’ll just have to play around with it for it to make more sense lol

tough cave
#

how could I approach this problem? Maybe terms to google for? on how to make my sprite change layer priority based on if its infront of behind the 'desk'?

buoyant knot
#

Levelmanager is very vague

buoyant knot
#

i forget the name of the video/feature

#

In a 2D game there is no real depth. All the object are only aligned on two axes and therefore one surface. In regard of the used camera angle it might be neccessary to create some kind of fake depth so that the player gets a feeling of 3D - or also called 2.5D.
In Unity this can be done very easy based on the Y coordinate. By adjusting the "Tra...

▶ Play video
#

maybe this will be what you need

tough cave
#

thanks!

neon ivy
#

I'm making a rhythm game and I'm having trouble syncing up the music to the notes.
is there a way to sample how long the music (audio source) has been playing? I can't find it in the documentation.
right now I'm just using a float that I add time.fixedDeltaTime to in fixed update but that isn't a good way to keep track of it and is already causing problems.

neon ivy
#

damn... I guess I was very blind xD

#

didn't see .time in the documentation

#

thanks UnityChanThumbsUp

bold nova
#

I am trying to create a universal object pooler. That object pooler class contains a list of my own class "Pool". It contains a List<Component>. The problem arises, when I try to instantiate game object with that component on it. and add to the the list. ObjectPooler gets some component as an argument

public static Component ProvideObject(Component component)
{
  GameObject newInstance = Instantiate(component.gameObject, position, rotation);

  pool.Instances.Add(newInstance.GetComponent<component.GetType()>); // add GO to the List<Component> of the pool class
}

This is the error I get :
Operator '<' cannot be applied to operands of type 'method group' and 'Type'.

rich adder
#

<component.GetType()> makes no sense

bold nova
#

yeah, that first thing that came to mind

shadow rain
#

hello so ive got a script for an object to point towards the mouse but its not pointing the way i want does anyone know how to fix this

bold nova
#

I just dont know how to pass a component in a method, instantiate a GO with that component and add that Go to a list of specific component

rich adder
languid spire
rich adder
#

without code at very least, we are just guessing

bold nova
#

yeah, it worked, thanks😁

shadow rain
final glade
#

Is it acceptable to send git repos to show code according to the rules?

polar acorn
eternal falconBOT
hallow totem
#

public List<Enemy> currentZombiesAlive;
What's wrong with this list?

rich adder
hallow totem
#

I don't know. :'3
I'm just following a tutorioal, though it was the name of the list, my bad.

rich adder
#

either tutorial is bad or you missed a step

#

should probably start with the basics of c# tbh like how to create a class etc

final glade
#

My game is a defense tower game between germs and tissues
Basically now I’ve designed a level but the issue is with the germs
The issue is there are 4 scripts and 2 objects/prefabs needed. 1 empty object with just the script to create a prefab in the scene to instantiate them in simpler words, another in assets below contains everything else. The issue is they don’t pass the rigid body 2d or any other scripts to the one in the scene although I made sure of it in the scripts any fixes?
The way i passed them is that I serializedfield everything I need in the one in the scene then I pass them to a parameterised function called InitializeObjects present in each of the other classes.

#

The other scripts as expected do not run because they’re not in the scene so how can I keep on calling the important functions in the other classes?

storm pine
#

Is there any way to get any inactive object by type through script?. I tried with FindAnyObjectByType but I found on the documentation that only works with active items. If there isn't any easy way my other option is to select it through the inspector using a variable

hallow totem
polar acorn
final glade
languid spire
storm pine
hallow totem
#

Found my issue, just needed to rename it.

#

I appreciate the help, sorry for being so clueless but I just want to get it done, I don't plan on working on anything serious in unity, just doing this in it because people I'm doing a project with wanted to work in it.

hallow totem
#
using System.Collections.Generic;
using UnityEngine;

public class ZombieSpawnController : MonoBehaviour
{
    public int intitialZombiePerWave = 5;
    public int currentZombiesPerWave;
    public float spawnDelay = 0.5f;
    public int currentWave = 0;
    public float waveCooldown = 10.0f;
    public bool inCooldown;
    public float cooldownCounter = 0;
    public List<Zombie> currentZombiesAlive;
    public GameObject zombiePrefab;

    private void Start()
    {
        currentZombiesPerWave = intitialZombiePerWave;
        StartNextWave();
    }
    private void StartNextWave()
    {
        currentZombiesAlive.Clear();
        currentWave++;
        StartCoroutine(SpawnWave());
    }
    private IEnumerator SpawnWave()
    {
        for (int i=0; i < currentZombiesPerWave; i++)
        {
            Vector3 spawnOffset = new Vector3(Random.Range(-1f,1f),0f,Random.Range(-1f,1f));
            Vector3 spawnPosition = transform.position + spawnOffset;
            var zombie = Instantiate (zombiePrefab, spawnPosition, Quaternion.identity);
            Zombie enemyScript = zombie.GetComponent<Zombie>();
            currentZombiesAlive.Add(enemyScript);
            yield return new WaitForSeconds(spawnDelay);
        }```
How is it not assigned?
polar acorn
# hallow totem

You have another ZombieSpawnController that does not have it assigned

hallow totem
#

Oh... How can I check where else this script is used?

polar acorn
#

Search t: ZombieSpawnController in the hierarchy

hallow totem
#

Tyvm.

woven crater
#

can i get the reference to the gameobject associated with the tile?
or can i get the specific tile in the tilerule for reference?

brazen canyon
#

Guys.
I need help !!
I have this script.
Does this script to create a Joystick.
But when I put the prefab into a Canvas, I can't use the Joystick
Is there anything else I need for it to work
Please help me

hallow totem
#
    {
        GetComponent<MouseMovement>().enabled = false;
        GetComponent<PlayerMovement>().enabled = false;
        GetComponent<Weapon>().enabled = false;
        playerHealthUI.gameObject.SetActive(false);
    }```
So I wanted to disable the weapon script like I disabled the movement scripts but for some reson with this one I got this when it triggered.
languid spire
plush hound
#

Does Physics2D.OverlapCircleAll require Rigidbodies on in-range colliders for them to be detected?

hallow totem
#

I'm not sure what you mean, I don't have any of them in this script.

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class Player : MonoBehaviour
{
    public int HP = 100;
    public TextMeshProUGUI playerHealthUI;
    private void Start()
    {
        playerHealthUI.text = $"Health: {HP}";
    }
    public void TakeDamage (int damageAmount)
    {
        HP -= damageAmount;
        
        if (HP <= 0)
        {
            PlayerDead();
            print ("is dead");
        }
        else
        {
            playerHealthUI.text = $"Health: {HP}";
        }
        
    }
    private void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag("ZombieHand"))
        {
            TakeDamage(100);
        }
    }
    private void PlayerDead()
    {
        GetComponent<MouseMovement>().enabled = false;
        GetComponent<PlayerMovement>().enabled = false;
        GetComponent<Weapon>().enabled = false;
        playerHealthUI.gameObject.SetActive(false);
    }
}```
keen dew
#

Which one is line 42?

hallow totem
#

Weapon.

languid spire
#
GetComponent<MouseMovement>().enabled = false;
        GetComponent<PlayerMovement>().enabled = false;
        GetComponent<Weapon>().enabled = false;

these three lines try to get a component from the gameobject this script is on

hallow totem
#

Oooh.

keen dew
#

The player doesn't have a Weapon component

hallow totem
#

Yeah I moved the script, thanks.

short hazel
#

Since you posted a screenshot of your Assets window with all your scripts I just want to make sure there is no doubt:
GetComponent does not look in your Assets but on the objects in your scene!

brazen geyser
#

Hello, I'm starting a project in Unity and when I press the space key it doesn't work and I can't find the error, in case someone could help me

Pass the code:

{
    public float speed;
    public float jumpForce;
    private Rigidbody2D rb;
    private float horizontalMovement;
    private bool grounded;

    private void Start()
    {
        // Obtener el componente Rigidbody2D del objeto
        rb = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        // Capturar el movimiento horizontal del jugador
        horizontalMovement = Input.GetAxisRaw("Horizontal");

        if(Physics2D.Raycast(transform.position, Vector2.down, 0.1f))
        {
            grounded = true;
        }
        else grounded = false;

        if (Input.GetKeyDown(KeyCode.Space) && grounded)
        {
            Jump();
        }
    }

    private void Jump()
    {
        rb.AddForce(Vector2.up * jumpForce);
    }

    private void FixedUpdate()
    {
        // Actualizar la velocidad del Rigidbody2D en el eje horizontal
        rb.velocity = new Vector2(horizontalMovement, rb.velocity.y);
    }
}```
rich adder
#

also make sure your grounded is working

#

this can literally be
grounded = Physics2D.Raycast(transform.position, Vector2.down, 0.1f)

brazen geyser
#

Thank you very much <3

rich adder
brazen geyser
#

Yep

rich adder
#

nice

frank zodiac
#

my functions arent showing

rich adder
#

not the script from project folder

frank zodiac
#

ok ill try that and let u know how it goes

#

it works!

#

tysm :)

rich adder
plush hound
#

For some reason, Physics2D.OverlapCircleAll isn't returning all the colliders expected. Any ideas why? I have a Rigidbody on the GO calling the function, but no Rigidbodies on the expected colliders. I'm specifying a LayerMask, and I assigned all the expected colliders the layer in question.

frank zodiac
#

wait guys how can i make a tilemap have a layer for ground so that the player can stand on it, because my player just falls through

short hazel
short hazel
#

Yes the call is correct

plush hound
#

It's odd because it's recognizing something definitely outside its range without recognizing anything within

#

And then after some time the function actually starts returning stuff

short hazel
#

The mask includes the selected layers in the results, maybe you have it inverted?

plush hound
#

Yes, I only want the Germs layer

frank zodiac
#

how do i fix this

short hazel
frank zodiac
#

do i put 16:9 aspect?

short hazel
#

Are you in the Editor right now?

#

Should be at the top of the Game View

#

By default it's set to "Free Aspect" so it takes all the room you give it when resizing the tab

frank zodiac
#

ah i see okay then

#

also what do i set this value to

#

in the pixel perfect camera componenent

short hazel
#

No idea, see the documentation, maybe it has some tips about this

real falcon
#

how is this possible? do I not understand Vector3.Dot? it should be 1, shouldn't it? since both vectors are normalized?

real falcon
#

it seems to change as velocity decreases even though the DIRECTION isn't changing

short hazel
frank zodiac
#

my pixel art is in 32px

woeful terrace
#

Hi, I'm just trying to set up my visual studio as it was before. I had the minimap and I zoomed in a bit but I can't figure out how to do those simple things for the life of me.

These are the only ones I can really find and none of them works
View > Appearance > Zoom In (Ctrl+=)
click View. Click Appearance. Click Minimap.

Issue is I have no appearance when I click view. I apprechiate nay help (Not quite the toppic of the channel but I need help and this is the best fit I can find lol)

short hazel
frank zodiac
#

ok then

short hazel
woeful terrace
short hazel
#

If I remember correctly it's under the Text Editor > Scroll item

#

Checking...

#

Text Editor > [programming language] > Scroll Bars
"Use map mode for vertical scroll bar"

woeful terrace
#

Ah thank you very much

#

Do you know about the zoom however?

short hazel
#

Zoom will be at the bottom left of the code window when you have a file open

#

You can also Ctrl + Scroll Wheel while over your code to zoom in/out

woeful terrace
#

Yes there we go thank you very much 👍

blissful spindle
#

Hi, so bassicaly I have a script that I tought would check for name of the gameobject that its attached to and if its the same it will just print out a message in console but its not why? https://hatebin.com/zfgkuzaplo

eager wolf
#

why does this code break unity?

When i try to debug this manually, it shows me that the "coordsVisited" literally equals to "uhOh" how is that even possible?

short hazel
#

There seems to be a suggestion under uhOh in the while loop condition (see: 3 gray dots under the variable name). What does it suggest?

rich adder
short hazel
#

Make sure you saved, and that you were not in play mode while editing the code

rich adder
#

use the Type safety aspects to your advatage

languid spire
eager wolf
short hazel
eager wolf
#

Look, i just changed it to another number that is predictable. Every time my maze is done generating, this number will go to -1.

And EVEN THIS breaks the game

knotty ferry
#

need help how to make when A game Over screen pops up and the player coudn't use controls walk when player IsDead = true;

blissful spindle
rich adder
blissful spindle
short hazel
blissful spindle
eager wolf
#

it just hates me today

rich adder
knotty ferry
blissful spindle
short hazel
rich adder
#

not a good way if you have multiple different objects with same script

blissful spindle
blissful spindle
languid spire
frank zodiac
#

how do i import fonts into unity? do i import the .ttf file or the .fon file?

frank zodiac
#

oh wrong channel

frank zodiac
#

but thank you anyways

languid spire
rich adder
frank zodiac
blissful spindle
languid spire
frank zodiac
eager wolf
eager wolf
polar acorn
languid spire
digital wharf
#

I am trying to make the player's y rotation be the same as the camera's y rotation but the rotation keeps returning as a number between -1 and 1 ```
//relevant code
//cameraRot is a temporary var I am using to debug
public Transform cameraRotation;
public float cameraRot;

cameraRot = cameraRotation.rotation.y;

wintry quarry
languid spire
wintry quarry
#

That's not how Quaternions work

polar acorn
eager wolf
#

the "while" loop is meant to stop before the array is indexed with -1

wintry quarry
polar acorn
eternal falconBOT
languid spire
wintry quarry
#

Your while loop doesn't prevent it from being set to that inside the loop

short hazel
#

None of the code in the while loop touched that solutionNum variable
At least from what we can see

polar acorn
#

And since we don't have any other code that shows where it's being used we can only assume you've set it to -1 the line right before this so perhaps try not doing that

eager wolf
#

which is why, my "while" loop is meant to run "coordsVisited < uhOh" but that breaks

short hazel
#

What's the motto again? About causality

languid spire
short hazel
#

Maybe it's entirely unrelated lol

eager wolf
#

I also tried "solutionNum > 0" and that broke

eager wolf
polar acorn
wintry quarry
#

Which you MUST be doing else you'd freeze

eager wolf
wintry quarry
#

How?

polar acorn
wintry quarry
#

That's not possible since clearly all this other code is inside Move

short hazel
#

Remember, we are not in front of your screen!!!!

#

We cannot see everyhting you see

eager wolf
wintry quarry
#

Neither your loop nor your "uh oh" thing can affect anything inside Move

eager wolf
polar acorn
eternal falconBOT
wintry quarry
#

Yea

#

That's nothing bud

wintry quarry
rich adder
wintry quarry
#

Reading code isn't like reading a novel. We know how to skim through extremely quickly

eager wolf
eager wolf
#

it's the code right after that's actually causing the crash (in the start())

#

sorry guys

#

i guess the error in the "while' was stopping the other code from running

polar acorn
#

Okay, so, now that you've actually posted the code, solutionNum is literally never set to anything in this code. All you do is increment it in this script. So, a different script, or the editor, is setting it to -1

frank zodiac
#

why is there a red line

polar acorn
frank zodiac
slender nymph
#

use the quick actions to add the correct using directive

short hazel
frank zodiac
polar acorn
languid spire
#

Also, wtf is the point of the while loop in Move() ? It's only ever executed once

eager wolf
languid spire
polar acorn
#

Also, if a can only ever be 0 or 1, why is it an int

eager wolf
polar acorn
short hazel
#

Move is itself executed 200 times, but each time the loop runs once

polar acorn
#

meaning the loop runs one time

#

which means why is there a loop

languid spire
#

some of the shittiest logic I have ever seen, sorry to be blunt

eager wolf
#

yes

#

i 100% agree

#

i don't know how to code an efficient maze algorithm

#

this code was also written 2 years ago... i'm reworking it right now haha

short hazel
#

It's the easter egg that crashes the game if a cosmic ray hits and flips the bit at the memory location of that variable

languid spire
short hazel
#

If it's a simple 2d maze, you can look into recursive backtracking algorithms for carving through the walls randomly

frank zodiac
#

im trying to drag this text into this slot but its not working

slender nymph
#

that's the wrong variable type. TextMeshPro is the 3d version. use either TextMeshProUGUI or TMP_Text which it inherits from

#

also don't crosspost

frank zodiac
short hazel
real falcon
#

hm ok so I realized the problem with my previous code and now I am trying to get a value which essentially gives you a "simplified velocity" based on your actual difference in location between ticks

#

locationBasedVel = (transform.position - previousLocation) * Time.deltaTime;

#

I don't think multiplying by deltatime is correct though

#

should it be divided by it?

#

but then what if it's zero? I know that SHOULD be physically impossible but I want to account for it, knowing how code often works

#

I guess I need to take the magnitude of that vector as well, but regardless

eager wolf
#

this breaks my script, it previously worked, so idk why it does that. It's called on start()

https://hastebin.com/share/ametaqazaz.java

wintry quarry
wintry quarry
#

In which case it makes sense because that means you're moving nonzero distance in zero time which implies... nonsense

real falcon
vestal ether
#

If you knwo C# at a intermediate level will u be able to create games in unity proficiently

#

or does unity have extra stuff u have to learn when using C# when u create the game's stuff

real falcon
#

I would say it has a lot of "extra stuff" from my own expirience because while programming is pure logic, Unity is a game engine that has to work in a specific way due to technical limitations, and so you need to know how actual game engine stuff works

#

@wintry quarry my code seems to be spitting out nonsense unfortunately, do you see any problems here? or could it be the fact that I'm messing with the time scale?

#

nah it seems to be nonsense even when timescale is 1

wintry quarry
#

also where and when is previousLocation set?

#

and where is this code running

real falcon
#

this is called from Update, before the code that moves the collider

wintry quarry
#

also if you want the vector velocity you can do:

Vector3 diff = transform.position - previousLocation;
Vector3 velocity = diff / Time.deltaTime;``` no need for the magnitude aqnd normalization etc
real falcon
#

no, it appears to still randomly go low and high

#

my movement code is otherwise working, I can run in a line and accelerate fine etc.

wintry quarry
real falcon
#

UpdateGhost is called from Update

wintry quarry
#

also how is the object moving?

real falcon
wintry quarry
#

Is it Rigidbody motion?

real falcon
#

character controller

wintry quarry
#

Ok that might be the problem I think...

#

What happens if you do this code in FixedUpdate?

real falcon
#

I could try it, though I didn't do it there because I figured that was for the physics system. also, should I then remove the delta time? or just copy it as is

#

pasted as is, it seems to randomly zero out sometimes

#

instead of going low it will just go to zero

#

and then jump back up to a more reasonable speed

wintry quarry
#

ok FixedUpdate isn't right then

wintry quarry
#

how is it being calculated

real falcon
#

ground move and jump move basically calculate it with the input vector and friction

#

playerVelocity seems fine, it makes sense to me and it works as intended

wintry quarry
#

friction?

real falcon
#

the only reason I'm not using it is primarily because it has a negative up component usually since the character controller seems to need that in order to stay grounded

wintry quarry
#

Also if you have this playerVelocity variable already why not use it

real falcon
#

so you can stand on the ground and be still, yet the AI thinks you are moving downwards

wintry quarry
#

So why not just use this one

real falcon
#

because I do want the AI to be able to respond to jumping or falling

wintry quarry
#

You can also try this:

characterController.Move(...);
Vector3 velocity = characterController.velocity;```
real falcon
#

I wanted to just have a velocity which was based on actual position change, not the internal one that has to account for the nature of collisions and charcater controller and all that

real falcon
#

so does the character controller velocity basically get like clamped by move?

wintry quarry
#

Yeah it tells you how much it actually moved

#

not sure if it needs / Time.deltaTime or not

real falcon
#

awesome I think that works

#

no idea that existed, super helpful tbh

violet glacier
#

For a 2d game, is damage popup better as UI or regular component? I will instantiate a lot of damage popups at once

eager wolf
cosmic dagger
violet glacier
north oar
#

!ide

eternal falconBOT
north oar
#

how do i configure it

modest dust
#

By reading beyond the first sentence

ivory bobcat
#

Select the link that's applicable to you. Go through the process and make sure everything has been done.

#

For Visual Studio, the common misstep is with the Workloads.

cosmic dagger
rose galleon
#

How do I make a countdown system?

#

Or anything that counts time and triggers an action at the end of the time

slender nymph
#

create a float and subtract deltaTime from it in Update

ivory bobcat
ivory bobcat
# rose galleon Or anything that counts time and triggers an action at the end of the time

Self implemented timer:cs private void Update() { if(Time.time > next) { //Do something next += delay; } }Coroutine: https://docs.unity3d.com/ScriptReference/Coroutine.htmlcs private void Start() => StartCoroutine(Countdown(action, delay)); IEnumerator Countdown(Action action, float delay) { var next = new WaitForSeconds(delay); while(true) { yield return next; //Do something } }Invoke Repeating: https://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html```cs
InvokeRepeating("DoSomething", delay, delay);

> Invoke and InvokeRepeating do not stop after the game object is deactivated. On the other hand, this not true for coroutines. They stop after the game object is deactivated or destroyed.
A self implemented timer might be fine if you're simply expecting it to run once.
sterile kelp
#

hey uh, if one were to come across a file with a .bytes extension, how would one convert it to something humanly readable?

slender nymph
#

it depends on what the contents of that file actually are

sterile kelp
#

a text file

#

i mean just text

#

methinks?

slender nymph
#

i'm gonna go out on a limb and guess you've got a save file for some other game and you want to read it. but doing so will depend on how it was serialized

#

this is also not the place to get help with modding other people's games, it is a development server to help with ones own unity projects

sterile kelp
#

damn okay sorry

cosmic dagger
#

how do you not know the contents of the file?

glossy blaze
#

hey im going to use unity to make a one or two small projects for a portfolio i have a bit of exprience in python quite some more in visual coding will it be pretty hard to pick it up to make the projects

deft grail
glossy blaze
deft grail
glossy blaze
#

cool

teal viper
#

There is a "runtime fee"(which is applied under certain conditions), but it sounds like you're asking about something else judging from the context.

gentle stratus
#

whats the easiest way to check line of sight between two objects

#

i was thinking raycast but that only returns bools and itd return true regardless of whether or not theres a wall in between the two objects

slender nymph
#

raycast and check what was hit

gentle stratus
#

oh can i do that

#

i didnt see a method for checking collider

slender nymph
#

just compare tag or check for a specific type of component on the hit object

gentle stratus
#

ok thanks

sacred orbit
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Swinging : MonoBehaviour
{
    private Rigidbody rb;
    private bool swinging;
    public HingeJoint joint;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        swinging = false;
    }


    void Update()
    {
        if (Input.GetKeyUp(KeyCode.Mouse0) && swinging == true)
        {

            StopSwinging();
        }
    }

    void OnCollisionEnter(Collision other)
    {
        GameObject otherObject = other.gameObject;
       if (Input.GetKey(KeyCode.Mouse0) && swinging == false)
        {
            if (otherObject.tag == "Vine")
            {
                StartSwinging(otherObject);
            }
        }
    }

    void StartSwinging(GameObject otherObject)
    {
        swinging = true;
        otherObject.GetComponent<Rigidbody>().velocity = rb.velocity * 5;
        joint = otherObject.gameObject.AddComponent<HingeJoint>();
        joint.connectedBody = rb;
    }

    void StopSwinging()
    {
        Destroy(joint);
        swinging = false;
    }
}

Im trying to create a rope swinging script, to do this I am connecting the player to the rope with a hingejoint and setting the collided object with the same velocity as the player, but when the player connects, they hit the link of the rope and just stop all velocity. Does anyone have an idea to get around this? I tried making the rope istrigger on collision but its a bit janky when I do it that way. Code is Above

#

sorry for block of code :/

tame cradle
#

hi, i'm making a player controller with a rigidbody, but whenever i move into a wall my character just stops
here's my code: https://bpa.st/OOEA

#

i did try to use a constantforce but the force would keep increasing infinitely and become too fast

#

basically, how do i move a rigidbody with input without directly setting the velocity

#

(so it's smooth and stuff as well)

lunar apex
#

how do I do one of the fancy code bubbles

rich adder
#

!code

eternal falconBOT
rich adder
lunar apex
#

nah i dont get it

rich adder
#

just use a link ifyou're confused, its literally 3 backticks

lunar apex
#
        if (Input.GetKeyDown(crouchKey))
        {
            transform.localScale = new Vector3(transform.localScale.x, crouchYScale, transform.localScale.z);
            rb.AddForce(Vector3.down * 5f, ForceMode.Impulse);
        }

        //un crouch man
        if (headInRoof() && Input.GetKeyUp(crouchKey))
        {
            transform.localScale = new Vector3(transform.localScale.x, startYScale, transform.localScale.z);
        }
    }

    private bool headInRoof()
    {

        float headCheckDistance = startYScale - crouchYScale;

        RaycastHit hit;
        if (Physics.Raycast(transform.position, Vector3.up, out hit, headCheckDistance + 0.3f))
        {
            return false;
        }

        return true;
    } ```
#

there you go

rich adder
#

could've just edited your message

lunar apex
#

sorry

rich adder
#

have you tried drawing the raycast ?

#

use Debug.DrawRay, with the same values

lunar apex
#

question: I am trying to make something that can detect if the players head would be inside of roof if they uncrouched and if it would then the player should not uncrouch. I do not understand what is going wrong. If you need more context in code I can give it to you:

#

sorry i deleted my old question so I added it back

#

alr ill try it

rich adder
#

also I would not scale the entire object, I would just scale collider

lunar apex
#

you mean like this ``` if (Debug.DrawRay(transform.position, Vector3.up, out hit, headCheckDistance + 0.3f))
{
return false;
}

rich adder
opaque hinge
#

I am trying to use Unity's rule tiles and tile map system. I generated a grid of rule tiles, and I added a bool isBlocked. The problem I am encountering is that each rule tile that is generated follows the same script, so if I mark isBlocked as true, it is true for every tile. Is there a way around this using rule tiles, or would it be better to just generate the grid using gameObjects that can be individually scripted

abstract finch
#

Is there a way to share a float between two classes without them having to reference each other? I want float mouseSensitivity to be used in the camera and charactercontroller class. When either class modifies this value both will be affected by it

teal viper
abstract finch
teal viper
#

Struct is a value type

abstract finch
#

so the latter something like MouseValues with a float called mouse sensitivity in it?

teal viper
#

Yes. Though, you'd still need to pass an instance of it to both of your classes. For that either one of them would need to reference the other, or a class higher up the logical hierarchy would need to create and pass it to both.

abstract finch
#

I see, I've done this before so its not an issue for me

#

thanks ill go with that

#

i was wondering also about using a public static float, is this a viable method of doing it?

#

public static float mouseSensitivity= 3.14f;

hallow totem
#

Why is the text so smudgy? Is it the font size?

fair veldt
#

try increasing the font size and scale down the textbox with the scale tool

summer stump
hallow totem
#

I think there's only so far that could get me, it's better but still not great and this is font size 1000.

#

Okay the rest of the issue was the free aspect and view scale, my bad, thanks.

blissful spindle
#

Hi, is there any way of referencing a script that is attached to a prefab, so for example I want to increase the drop of my experience on killing an enemy but the enemy is a prefab so I cant find it in my game scene. How would I reference it?

slender nymph
#

wait, if you want to do this on killing an enemy, why do you need to reference the enemy prefab?

blissful spindle
frank zodiac
slender nymph
#

which script

blissful spindle
slender nymph
#

are you trying to reference a component on the Enemy from the Player or are you trying to reference something on the Player from the Enemy?

slender nymph
#

you know you could have just answered my question instead of dropping those links and i could have provided the answer to your issue

blissful spindle
slender nymph
#

you don't. you instead reference whatever spawns the enemy objects. and have that object tell the prefabs how much experience to drop whenever it spawns them

blissful spindle
#

oh, I see

green ether
#

except for when you upgrades are changing

green ether
#

When you can get it after enemies already spawned/ as an equippable that you can equip/ unequip

#

You would want a different solution

blissful spindle
green ether
#

Then i guess its not too noticable?

blissful spindle
green ether
#

But could be weird if you get the upgrade and dont feel the effects straight away

#

Like: You upgrade xp gain but dont actually get more from all the enemies who are already spawned

blissful spindle
green ether
#

yeah exactly

slender nymph
#

the spawner object can also keep track of what it has spawed and tell those objects too

#

so either way you shouldn't be modifying the prefab itself

blissful spindle
rapid pendant
#

Hey everyone, just joined here. I have a MERN Stack background. Now, I am shifting to XR. I am aware of fundamental tools like Unity, Unreal, Lens builder, SparkAr, Blender, C#.

But I am looking for some learning resources in XR to start off.

blissful spindle
slender nymph
#

modifying the prefab is going to have unintentional consequences that are even more complicated to figure out

blissful spindle
blissful spindle
#

well, anyways thx for helping me guys

hallow totem
#

How can I get this

#

to show up on top of this?

#

They're on the same canvas.

slender nymph
#

this is a code channel

fair veldt
modest dust
#

Or rather below

#

Read about the draw order

violet glacier
#

I wanted to reuse an animation for another game object so I ctrl c and ctrl v, put it into the animator controller of new object, but then it broke all the other transitions, anyone know why or how i can fix this? When I delete the animation in the controller, it went back to normal

slender nymph
#

this is a code channel. but just drag the animation clip into the animator controller from the assets folder, don't bother with copy/pasting the clip from one controller to another

molten dock
#

how would i have a navmesh agent randomly choose to go to fight one of four targets

frank zodiac
hallow totem
hallow totem
topaz mortar
#

is it common to define lists or dictionaries as var? why?
var itemsToRemove = new List<int>();

frank zodiac
deft grail
deft grail
hallow totem
frank zodiac
#

oh i see, thanks

topaz mortar
deft grail
# topaz mortar so it's totally fine to define it as var?

var means basically it will automatically pick the appropriate variable type instead of you having to manually do it
var something = 0; would make something an int
var something = new GameObject[]; would make something an array of GameObjects
Just saves you time by trying to define the type yourself

topaz mortar
#

yeah I understand what it does, I'm asking if it's good practice to do it

deft grail
knotty gust
languid spire
oak fulcrum
#

Hi, I literally just started with learning Unity. I'm following a tutorial and just wrote my first script (copied it exactly from the video) but I got an error and am unable to see the ''Move Speed'' bar that he has in his tutorial. I also get an error that says ''Assets\Script\PlayerControl.cs(17,40): error CS1012: Too many characters in character literal''. I'd appreciate it a lot if someone could help me!

First picture is from the video, second is mine, third is the script.

oak fulcrum
knotty gust
#

had to set an index for the struct and reference that in the update

#

thanks tho

deft grail
#

specifically the part in brackets ()

#

check the tutorial and make sure its 100% same (its not)

languid spire
oak fulcrum
#

Yeah looking back I thought that might've been it, but I tried doing '' and it just took it as ' ' instead (two ' seperate)

#

Wait

#

No I think I might got it

#

Yes I got it!

#

Thanks!

rotund egret
#

How do i make an object To destroy its own self only its self after it hits a specific thing?

deft grail
#

and for specific thing you can check the tag/layer of the thing you collide with

rotund egret
#

i did this

deft grail
rotund egret
#

wdym?

deft grail
rotund egret
#

huh

deft grail
rotund egret
#

like this ?

deft grail
#

yeah, just make sure you actually have the tag Energy_Ball on the object you want to collide with

strong wren
#

How do i hide TextMeshPro?

#

like in code

#

cause i cant just do

deft grail
strong wren
deft grail
#

it works on all GameObjects

strong wren
#

i beg to differ

deft grail
# strong wren

you are trying to disable the text itself, disable the object instead

strong wren
#

you mean the Renderer

deft grail
strong wren
strong wren
deft grail
strong wren
#

oh

#

i need to make a gameobject for it right?

deft grail
#

which you can do by .enabled

rotund egret
#

Here is a video of my issue

#

The thing dident work

deft grail
rotund egret
#

and yes ik im very messy

#

im still a beginner

deft grail
burnt vapor
#

Of the text

rotund egret
#

Dont ask Why

#

Up W Down S Right E left Q

patent compass
rotund egret
deft grail
rotund egret
#

Using transform

deft grail
strong wren
#

Countdown.SetText("Wave " + WaveCounter + " Starts In " + RoundDelay.ToString("0")); hey guys does anyone know why when i start the game the spaces inbeetween get removed?

#

instead of beaing Wave 1 Starts in 10

#

its Wave1Startsin10

rotund egret
storm pine
# strong wren ```Countdown.SetText("Wave " + WaveCounter + " Starts In " + RoundDelay.ToString...

If you use SetText you have to use it this way: http://digitalnativestudios.com/textmeshpro/docs/ScriptReference/TextMeshPro-SetText.html
If you want to use concatenating you can try with Countdown.text = "Wave " + WaveCounter + " Starts In " + RoundDelay.ToString("0");

rotund egret
#

Im having issues with the collogeon and destorying not the physics

#

idc about the balls movment

deft grail
#

so you do care about physics

strong wren
#

Countdown.text = WaveCounter.ToString("Wave " + WaveCounter + " Starts In " + RoundDelay.ToString("0")); like this?

deft grail
#

and the movement of it affects if it collides or not

storm pine
hexed terrace
#

Or this more readable way
Countdown.SetText($"Wave {WaveCount} Starts In {RoundDelay}");

storm pine
strong wren
#

i need the toString(). so it wont show me the decimals of the countdown

storm pine
honest haven
#
    {
        if (GameManager.instance.battleActive && !battleLoading)
        {
            battleLoading = true;
            GameManager.instance.battleStarter = gameObject;
            StaticBattleEnemys.rewardEXP = rewardXP;
            StaticBattleEnemys.playerPosition = GameObject.FindWithTag("Player").transform;
            StaticBattleEnemys.enemies.AddRange(battleEnemys);
            StaticBattleEnemys.SplashScreen = battleSplash;
            StaticBattleEnemys.rewardItem = rewardItem;
            StartCoroutine(LoadBattle());
        }
    }``` Hi i have a battle starter script and im making a ref to a game object in my gamemanager ``` public GameObject battleStarter;``` but when i enter a new scene some times its there and some times its not, my game manager is DDOL.
#

ok in the hierachy if i select another game object that also seems to make the ref becoming missing also.

rich adder
honest haven
#

Thanks i think i was taking to you yesterday you said this would be a good way to store a ref of a game object.

languid spire
honest haven
#

yh its temp

rich adder
honest haven
#

yh i am destroying the old one

rich adder
#

thats whats breaking it

honest haven
languid spire
#

well, thats why you lose references to objects in the destroyed scene

honest haven
#

so the top scene is never destroyed that just holds things instead of using ddol. then the scene underneath is the scene that im swapping out but also hods that game object

languid spire
#

tbh I would expect code like this to be in a delegate to onSceneLoaded so that any lost references could be fixed up using the newly loaded scene

honest haven
#

thanks i will fix that

#

i am just trrying to get this to work then i will refactor as my scene loading is hard coded too at the momnent

rich adder
honest haven
#

yes so that is what im trying to do. i seem to have that all in place apart from 'Store enemy'

#

but other then SO i dont no what else to do. and if i have 10 NPCs that would be 10 SO
seems messy

#

like you said yesterday

rich adder
#

Shouldn't be a problem you can store a whole array.
How would you do encounter with 10 enemies in the first place anyway?

honest haven
#

its a shame static does hold gameobject refs

rich adder
#

I mean, you can store it in a static.. its just going to have the same issue

honest haven
#
{
    public static List<GameObject> enemies = new List<GameObject>();

    public static GameObject SplashScreen;
    
    public static int rewardEXP;

    public static Transform playerPosition;

    public static GameObject rewardItem;

    public static void ClearEnemies()
    {
        enemies.Clear();
    }
}```
#

enemies are not the same as the ref

rich adder
#

why is everything static

#

dont you have a singleton ? use that

weak grove
#

how is the object inspector and the C# code for an object related? am a noob, what is the object inspector showing me ? all the variables in the C# code?

rich adder
weak grove
#

fields are variables right ?

rich adder
#

yes

honest haven
#

So the enemies are prefab battle chars not npc enemeies. splash screen is just a splash screen each npc has there own. reward EXP is an amount you get when you win. rewardItem is the item the npc drops when they lose they are all attached to the npc

rich adder
#

public or [SerializeField] private are shown in inspector

weak grove
#

@rich adder ty 😄

#

am on day 2 of learning haha

rich adder
#

major thing is , Unity cannot serialize Properties so if you use those and don't see them in the inspector. That is why

weak grove
#

ah i see

rich adder
#

a prop is for eg public string HelloWorldText {get; set;} = "HelloWorld"

weak grove
#

ah ok ty

#

back to unity 😄

rich adder
#

anyway back to the issue, if you do one encounter of 10 enemies, how do you plan on doing that

honest haven
# rich adder dont you have a singleton ? use that

So just to be clear becuase maybe singletons are not clear to me. i thought that they can be only used on things like gamemanager, player etc... because there is only one of them. So becuase there can be 10 npc's. i thought that singleton would be bad pratice am i wrong?

rich adder
#

anything you do in StaticBattleEnemys has to be reset manually

#

static will not change/reset through scene changes

honest haven
#

my first original question was how can i pass data between scence somebody said use static

#

so i did that then got to the point ref didnt work. and now im here with that one

rich adder
#

well I wouldnt have suggested a static

#

I would've suggested a DDOL

honest haven
#

no it was not you

rich adder
languid spire
#

would not have made any difference, gameobjects which are not passed from scene to scene would still lose their references

rich adder
#

unless you bring the enemy with you on the DDOL

#

but you should be fine if you just dont unload the scene tbh

honest haven
#

see i also tried a ddol at one time and it did not work, but it was not a singleton

#

im not sure if they have to be

languid spire
#

you can also move scene for gameobjects if you use additive loading, no need for ddol

rich adder
#

yes that was the original thought

honest haven
#

ohh you mean pass the game object before a scene is loaded

rich adder
#

you said you were loading batle scene additive so I have no idea why you unloaded old scene

languid spire
#

no, load the new scene additively, move the gameobject(s) from the old scene to the new one, destroy the old scene

rich adder
#

they need to go back to old scene thats why

#

think Pokemon battle scene

honest haven
#

ok so fen told me about additve scene loading so i went down that road but if you unload a scene you destroy it. But then i thought it would be harder to not ref every object to deativate them

rich adder
#

just maybe some bools to tell if the enemy that came with you was killed or whatever

honest haven
#

So if i didnt do what steve said and move the object. How do i deacive the scene with out destroying it

#

deactivate

rich adder
#

why do you need to deactivate it

honest haven
#

because the battle scene sits in the same pos as the old one so i see both at the same time

#

can i get back to you in 15 mins i just got to do a working meeting.

rich adder
#

if you want to be able to unload the scene without losing references to enemies, you could technically put all enemies in a DDOL so they can move whereveer without destroying

#

or put your battle scene in a different spot completly

#

old school pokemon for example doesn't use the same scene(probably) since the background/positioning changes

languid spire
#

'or put your battle scene in a different spot completly'
that would be the optimal solution

deft glen
#

does anyone know why this could be happening? its giving me absolutely no information

#

VS is giving me no errors either..

rich adder
#

its cutoff

deft glen
#

first 2 are when i try to do a build, last one is when i try to enter play mode

rich adder
#

restart unity, see if you get more errors or safe mode

deft glen
#

restarting seemed to fix it, probably should have tried that before posting here lmao

rich adder
#

good ol restart

icy wedge
#

hello guys, I'm having trouble activating a canvas from c#. If for example I toggle the small box next to the name, the canvas is visible on start and if i do canvas.SetActive(false); il will successfully disappear. But if I start with an inactive canvas, where i untoggled the box from start and do canvas.SetActive(true); it will not find it. I'm getting the canvas from canvas = GameObject.Find("UpgradeCanvas");. Any idea ?

The purpose of this is when I click on a box (which is a chest in the game), it should open a window that will be like an inventory or something like that

rich adder
#

also its a shitty method anyway

icy wedge
#

how do people do usually for that ?

rich adder
#

Just link it in the inspector

icy wedge
#

by adding a button component to my box ?

rich adder
#

[SerializeField] private Canvas canvas

#

drag n drop

#

if it isnt possible use a component FindObjectOfType<T>(true)

icy wedge
#

i found a workaround because it did not work, i just keep it active and put it to inactive on start(), then whenever you click the object it somehow finds it

iron mango
#

i want to run a function every 1.5 seconds, what is the best way to do that? i thought of invokeRepeat, but this uses " ", does this mean it's searching for the function by name? is it better for performance to code a timer or just use that?

rich adder
#
  void StartRepeater()
    {
        StartCoroutine(RepeatTimer(1.5f));
    }
    IEnumerator RepeatTimer(float time)
    {
        while (true)
        {
            yield return new WaitForSeconds(time));
            //do something
        }
    }```
wintry quarry
iron mango
#

i was asking because it's a strategy game and performance is very important ._. so yeah idk which one is best for that

wintry quarry
#

the Update one will be slightly better

#

it doesn't allocate garbage

#

The timer is also more accurate

#

though you can get an equally accurate timer and not allocate garbage in a coroute too - you just need to not use WaitForSeconds

final kestrel
#
private void HandleMovementInput()
{
  currentInput = new Vector2(walkspeed *Input.GetAxis("Vertical"),walkSpeed * Input.GetAxis("Horizontal"));
  float moveDirectionY = moveDirection.y;
  moveDirection = (transform.TransformDirection(Vector3.forward)*currentInput.x) + (transform.TransformDirection(Vector3.right) * currentInput.y);
  moveDirection.y = moveDirectionY;
}

I was watching a video on First person controls. Why do we store the moveDirectionY before calculating the moveDirection? and also set it back to where it was again at the end?

#

cos on moveDirection we already decide which way is forward and horizontal

wintry quarry
#

alsp transform.TransformDirection(Vector3.forward) can be simplified to transform.forward

#

likewise for transform.TransformDirection(Vector3.right) and transform.right

final kestrel
#

is it for gravity and such?

wintry quarry
#

in fact I'd say this:

moveDirection = (transform.TransformDirection(Vector3.forward)*currentInput.x) + (transform.TransformDirection(Vector3.right) * currentInput.y);```
Would be better written as
```cs
moveDirection = transform.rotation * new Vector3(currentInput.x, 0, currentInput.y);```
wintry quarry
final kestrel
#

Ah okay so it has got nothing to do with restricting vector3 direction with vector2 input?

icy wedge
#

hey, let's say i have a Panel inside of a canvas, and I would like in c# start() to create a checkbox and place it inside of the panel ?

here is the code I'm using but it complains about NullReferenceException on the line GameObject checkboxGO = Instantiate(checkboxPrefab, panel.transform);

public class MixingTable : MonoBehaviour
{

    GameObject canvas;
    public GameObject checkboxPrefab;

    // Start is called before the first frame update
    void Start()
    {
        canvas = GameObject.Find("MixingTableCanvas");
        canvas.SetActive(false);

        GenerateCheckbox();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void OnMouseDown()
    {
        canvas.SetActive(!canvas.active);
    }


    void GenerateCheckbox()
    {
        GameObject panel = GameObject.Find("Panel");

        GameObject checkboxGO = Instantiate(checkboxPrefab, panel.transform);

        RectTransform rectTransform = checkboxGO.GetComponent<RectTransform>();
        rectTransform.localPosition = Vector3.zero;
        rectTransform.sizeDelta = new Vector2(30, 30);
        
    }
}

rich adder
icy wedge
#

checkboxPrefab is probably null since it does not exist anywhere in the project, in fact i want to create the checkbox from here

rich adder
icy wedge
#

no

rich adder
#

so make the prefab lol

icy wedge
#

but it is just a toggle from ui, do i have to instanciate it in the hierarchy ?

#

the point is to create x amount of checkboxes like that

rich adder
#

if you want to create them via code yes make a prefab of a single checkbox and place it in field (from the project window not hierarchy)

#

ofc ideally youd have a container object with a custom script though so you can mess with that script directly

eternal falconBOT
latent epoch
#

Hey yall I've been having some issue with this code for the past few days. I've managed to work out some minor errors but for some reaosn this one is really stumping me. I'm following a YT tutorial and just copying the code, and going through it real slow. My issue is that I keep getting "Unreachable Code detected" and "Not all code paths return a value"

I apologize if this is not the place, I'm just lost and have been struggling to find anything online that has been able to help me solve this on my own.

error 1 "for(int x = 0; x < WorldGenerator.ChunkSize.x; x++) - Unreachable code detected"
error 2 "ChunkMeshCreator.CreateMeshFromData(int[,,]) - not all Code paths return a value"

public  Mesh CreateMeshFromData(int[,,] Data)
    {
        List<Vector3> Vertices = new List<Vector3>();
        List<int> Indices = new List<int>();
        Mesh m = new Mesh();
        

        for(int x = 0; x < WorldGenerator.ChunkSize.x; x++)
        {
            for(int y = 0; y < WorldGenerator.ChunkSize.y; y++)
            {
                for(int z = 0; z < WorldGenerator.ChunkSize.z; z++)
                {
                    Vector3Int BlockPos = new Vector3Int(x, y, z);
                    for (int i = 0; i < CheckDirections.Length; i++)
                    {
                        Vector3Int BlockToCheck = BlockPos + CheckDirections[i];
deft grail
rare basin
#

is there a WaitUntil for coroutines but with unscaledDeltaTime?

#

cannot find anything :/

wintry quarry
rare basin
#

No, I wan't a bool predicate

icy wedge
latent epoch
rare basin
#

yield return new WaitUntil(()=> hasLoaded)

wintry quarry
#

You can write whatever you want

rich adder
deft grail
rich adder
#

its up to you which component you want to grab

rare basin
#

works in Update