#archived-code-general

1 messages · Page 302 of 1

merry stream
#

so to do spacial audio, should everything that plays a sound have an audio source or is there a way to play a sound specifying a location

#

or would that require insantiating an empty game object which is a waste of resources

spring creek
#

It's fine somewhat sparingly

merry stream
#

well I would use it for every sound in my game, so better to go the audio source on everything route?

#

100s of projectiles hitting making sounds etc, id imagine thats too much for no reaosn

spring creek
merry stream
#

ah that could be interesting, its a 2d game so it could

#

like have a few in each corner and sides to create the effect

#

but then wouldn't you have to calculate which one to play the sound from based on the location where it "should"?

latent latch
#

id check if an audio was played recently and just play one clip

merry stream
#

wdym?

latent latch
#

if you got multiple things hitting a wall in one frame then playing the audio clip 100x times seems excessive

glossy gust
#

i would normally serialize the field

#

but i can't drag that in the inspector

#

since it is not present before startinfg

merry stream
#

but im using an audio singleton and am trying to move away from that

#

and include spcial audio since right now everything just plays at the player

latent latch
#

ah, ok. I've not really touched audio. It's only one of those things I consider the polish of the game

merry stream
#

that is true

#

trying to get the game in a somewhat decent state though

merry stream
#

avoiding instantiation over and over

latent latch
#

I've been told that audio itself requires a bit more handling with pooling as the clip themselves can be rather large when loaded

merry stream
#

handling as in?

latent latch
#

not have all the audio loaded at once

merry stream
#

well I have all my audio stored in an SO

#

so it would fetch from that

latent latch
#

right, but eventually you do want to use asset bundles as having all your assets loaded at once is something you eventually have to fix

merry stream
#

ah i see, i dont know if my game will grow to be that large

latent latch
#

audio, textures, and models are usually the main culprit, but mostly textures

merry stream
#

yea, my game is 2d pixel art so I don't think that will be the issue

spring creek
merry stream
#

ill consider it though

#

perhaps my SO can load the audio in from resources only when it is requested by a source?

#

and it will cache it in a dictionary once its loaded for the first time

latent latch
#

I loaded vfx by asset bundles through checking the ability I am using then loading it in then adding it to the pool

#

stuff like that

merry stream
#

so are asset bundles more of a editor optimization or actual delivery optimization

latent latch
#

it's more specific to runtime performance

#

another optimization

#

(more noticable on mobile and webgl)

merry stream
#

but if everything just loads when the game starts up, there won't be any lag during gameplay? or am i missing something

latent latch
#

that's true, but you don't want to have more stuff loaded into mem than you need if you're not using it

merry stream
#

is everything from resources loaded in on start in a build version?

latent latch
#

even if mem is pretty abundant, and that cacheing is preferred, there's no reason to have all your 8k tree textures loaded when you're in the cave section of your game.

merry stream
#

ah i see

#

okay

#

though its more relevant for 3d games with good graphics id assume

glossy gust
#

thanks

latent latch
#

still, no reason to have all of your large textures or full soundtrack scores loaded in all at once

spring creek
high condor
#

is there a way to change just the alpha color of a sprite renderer?

leaden ice
#

same way you change any other part of the color

#
Color c = myRenderer.color;
c.a = whatever;
myRenderer.color = c;```
high condor
#

thanks; before, i had tried to convert it through doing something like sr.color.a = new Color(blah blah blah)

spring creek
#

That is fine

high condor
#

or yea thats what i meant

#

but no that wasnt working for me

spring creek
high condor
#

it said that spriterenderer.color doesnt work cuz it's not a variable to be changed, just a return statement

spring creek
#

Because you can certainly assign to color (as praetor just wrote)

high condor
leaden ice
#

So exactly what Aethenosity said.

high condor
#

yea :p

spring creek
#

Also keep in mind, color is 0 to 1

#

Not to 255

leaden ice
#

sr.color = new Color(sr.color.r, sr.color.g, sr.color.b, newAlpha); is an option but ugly and inefficient

high condor
#

oops

leaden ice
#

but yeah 255 should be 1

high condor
#

i just thought it would work because i thought it would just count sr.color as a Color variable instead of a return

#

the more you know

leaden ice
#

so it's actually a function

#

it's a bit like this

class Renderer {
  Color c;

  public Color GetColor() {
    return c;
  }
}

// some other code
void Example() {
  Renderer myRend = ...;
  myRend.GetColor().a = 100; // this doesn't work because Color is a struct. You are just modifying a copy
}```
#

The property hides that away sneakily

merry stream
#

why is that when i use the profiler, my game lags like crazy making it super hard to tell whats actually causing the lag

ocean hollow
#

not a coding question

leaden ice
merry stream
#

obviously its not

leaden ice
#

well it could be...

gusty aurora
leaden ice
spring creek
leaden ice
#

every one of those sr.colors is a call to the property getter and a copying of the whole Color struct

dim spindle
merry stream
#

it was spamming log messages causing lag

floral raft
#

Hello Need help!

#

I have made the Main menu and there's an object who's not in scene but associated with the game screen and it's in start method it asks for for two components in the gameplay screen, i thought the problem fixed already when there's a method finds an object with tag

#

I have made two scenes one for main menu and the other gameplay when i click play

ocean echo
#

is it possible to code somethign where when you click on the button you switch scenes but theres also a fade animation between them?

floral raft
# floral raft

I get this message on console screen in main menu but when I click play button which switches me to the other scene the problem will gone.

#

The file that has 'PepeTrigger' script and its not in the scene

#

this is in 'PepeTrigger' script, I don't know why it executes itself in main menu screen when she is not in the main menu

spring creek
# floral raft

Can you show the editor in the scene you get the error?

spring creek
#

Easiest is to fade out to black, switch scenes, fade in from black

#

But otherwise you can do an additive load and the unload with each kinda crossfading

ocean echo
#

i see ty

floral raft
#

When I press play button the console error goes away

spring creek
floral raft
#

hold on

spring creek
# floral raft

Ok, can you show the inspector for the "MainMainueLogic" object

floral raft
#

PipeTrigger script is on an Object that is not in the scene and I made it that way so it clones forever

#

sure

merry stream
#

does anyone have some intermediate level sources for unity? most of the stuff on youtube includes a lot of bad practices and is more geared towards absolute beginners

spring creek
merry stream
#

nope, will do

spring creek
#

Or sebastien lague

floral raft
merry stream
spring creek
#

So it can't find it

#

Oh wait

#

Doesn't have the LogicScript either

floral raft
#

LogicScript on the gameplay scene

#

and the other scene is off

#

I think the object that is not on the scene executes itself no matter what

spring creek
#

Yeah, in the main menu scene hierarchy search, type t:PepeTrigger

spring creek
floral raft
spring creek
floral raft
floral raft
#

hold on will write it on mainmenu

#

Still the same

floral raft
#

The game still playable its okay, but it's bit annoying in editor

spring creek
#

Ohhhh wait

#

It pops up after spawning a pipe of course

#

So yeah, won't show in the hierarchy view at first

floral raft
#

Oh no, the main menu will look ugly after removing spawning pipes

spring creek
#

Kind of a dirty hack

#

But quick and easy

floral raft
#

You couldn't say it any better

#

I'm the creator of that thing, but you could find it and that shows how good you're 🙂

#

Thank you for giving me the reason + the fix

#

Hope you have a nice day! Thank you so much.

spring creek
#

No problem. Best of luck

floral raft
floral raft
spring creek
#

Ah nice choice

plain ibex
#
public class Enemies : MonoBehaviour{
[SerializeField] private BalletScript balletScript;
[SerializeField] private GameObject balletObject;

public void SpawnAndConfigurePrefab()
    {
        BalletScript instance = Instantiate(balletScript);
        instance.Initialise(balletObject);
    }
private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.CompareTag("Ballet"))
        {
            Destroy(balletObject);
            enemyHealth -= 60;
        }
    }}```
```cs
public class BalletScript : MonoBehaviour
{
public GameObject balletObject;
public void Initialise(GameObject balletOps)
    {
        balletObject = balletOps;
    }
}```
#

its not working

carmine iris
#

Hello guys I have a question. As you can see there is 3 lines in the game. When the player taps to left of the screen, the ship will go to one line left. If the player taps to right of the screen, the ship will go to one line right. For this what methods and strategies that I should follow? How can I do this? I tried to make it with new input system but I am confused.

plain ibex
leaden ice
spring creek
#

What IS balletObject?

leaden ice
carmine iris
#

I made something like this. Would it work? Also how can I simulate mobile touches from computer?

spring creek
#

I asked what balletObject is...

prime sinew
# carmine iris I made something like this. Would it work? Also how can I simulate mobile touche...

Using the Device Simulator in Unity, you can now view, simulate and change the behavior of your game in various mobile devices! Device Simulator aims to give an accurate image of how an app will look on a device.

Game content from the title Neonverse by Pixel Reign and Tamasenco

Learn more about Device Simulator and its configurations here!
ht...

▶ Play video
#

i'm afraid multi touch isn't testable though, I think, if that's what you mean by mobile touches

carmine iris
#

ohh yes let me check it thanks

plain ibex
spring creek
lofty crest
#

is there a way for me to change a whole bunch of sprite renderers at once using c#

something like void
FlashWhileInvincible()
{
sr.material.color = pState.invincible ? Color.Lerp(Color.white, Color.black, Mathf.PingPong(Time.time * hitFlashSpeed, 1.0f)) : Color.white;
}
but for a whole list of sprite renderers

spring creek
#

The thing you created

#

Unless I am misunderstanding you

plain ibex
# spring creek Sorry, edited. But you want to destroy instance
public void shotButtonClick()
    {
        GameObject last = Instantiate(balletObject, balletSpawnpoint, Quaternion.identity);
        rb = last.GetComponent<Rigidbody2D>();
        rb.velocity = new Vector2(dirTargetObj.transform.position.x - balletSpawnpoint.x, dirTargetObj.transform.position.y - balletSpawnpoint.y).normalized * atisHizi;
    }```
Actually, i instantiate balletObject in different function.
plain ibex
spring creek
plain ibex
#

because if prefab is in assets i cant assign gameobjects to it

spring creek
#

To clarify, ALL prefabs are assets btw

plain ibex
#

and there is no errors but it doesnt destroy balletObject

spring creek
#

balletObject is the prefab, right?

plain ibex
spring creek
#

Destroy instance

#

The object you created and named instance

plain ibex
spring creek
#

"Didn't work" is always an unhelpful response

plain ibex
spring creek
#

Share the whole code as it is now

plain ibex
# spring creek That couldn't have been the only change without getting a compiler error
using UnityEngine;

public class Enemies : MonoBehaviour
{
    public int enemyHealth;
    [SerializeField] float enemySpeed;
    private Rigidbody2D rb;
    [SerializeField] private BalletScript balletScript;
    [SerializeField] private GameObject balletObject;
    private float randomTowerY;
    BalletScript instance;

    public void SpawnAndConfigurePrefab()
    {
        instance = Instantiate(balletScript);
        instance.Initialise(balletObject);
    }
    private void Start()
    {
        randomTowerY = Random.Range(1.85f, -3f); 
        rb = GetComponent<Rigidbody2D>();
        rb.velocity = new Vector2(7.75f - transform.position.x, randomTowerY - transform.position.y).normalized * enemySpeed;
        balletScript = GetComponent<BalletScript>();
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.CompareTag("Tower"))
        {
            Destroy(gameObject);
        }
        if (collision.collider.CompareTag("Ballet"))
        {
            Destroy(instance);
            enemyHealth -= 60;
        }
    }

    private void Update()
    {
            if (enemyHealth <= 0)
            {
                Destroy(gameObject);
            }
    }

    private void OnBecameInvisible()
    {
        Destroy(gameObject);
    }
}
spring creek
#

Do Destroy(instance.gameObject)

plain ibex
spring creek
plain ibex
spring creek
#

Ok, and line 43?

plain ibex
spring creek
plain ibex
#

and it called in

carmine iris
spring creek
plain ibex
#

oh it didnt call

spring creek
#

Yep. Thus instance is never assigned

plain ibex
# spring creek Yep. Thus instance is never assigned

ArgumentException: The Object you want to instantiate is null.
UnityEngine.Object.Instantiate[T] (T original) (at <f712b1dc50b4468388b9c5f95d0d0eaf>:0)
Enemies.SpawnAndConfigurePrefab () (at Assets/Scripts/Enemies.cs:15)
Enemies.Start () (at Assets/Scripts/Enemies.cs:20)

#

line 20 : SpawnAndConfigurePrefab();

#

15: instance = Instantiate(balletScript);

spring creek
#

It's a prefab, so it CAN be

#

And MUST be

plain ibex
spring creek
#

I really don't understand what the goal is here then

plain ibex
#

you asked is balletObject prefab

spring creek
#

This whole script is quite convoluted

spring creek
plain ibex
#

btw ballerObject isnt prefab too

spring creek
#

Why are you instantiating from something that is not a prefab
Let's start with that

plain ibex
spring creek
#

Problem solved

cosmic rain
spring creek
#

Using a scene object to instantiate from is risky either way. What if it gets destroyed?

Gotta be a good reason to do it that way. If not, just make it a prefab

plain ibex
spring creek
#

If anything

plain ibex
#

but if i dont change i cant assign it in inspector

spring creek
plain ibex
spring creek
plain ibex
spring creek
#

Prefabs can be dragged in

#

No worries at all.

#

Prefabs cannot reference SCENE objects (like the link you sent)

#

But prefabs can reference prefabs

#

And scene objects can reference prefabs

plain ibex
spring creek
#

Prefabs are in the project window only

#

Ever

#

Once the object is in the hierarchy (as an actual object, not a reference), it is no longer a prefab, it is an INSTANCE of a prefab

spring creek
#

I gotta go to bed. Hopefully this made sense.
Good luck!

plain ibex
#

thank you very much

latent latch
#

Prefabs can reference anything part of that prefab, but they cannot reference anything else if not on a scene

#

it's basically a bunch of instances that exists in that prefab alone

#

which is why it can live outside of the scene, in your assets

#

Because it can live in this asset space, it means your scene objects can directly reference these prefabs in your assets, but not vice versa because a scene reference is never guaranteed as you can have many

#

Does sound somewhat logical that a prefab could contain scene elements because not everyone uses multiple scenes, but I guess that's just by design.

#

and it's not like scene object -> prefab reference is fail safe either since you can load / deload assets at runtime

dense estuary
#

I am already doing that. Since the object isnt parented to anything, localPosition is equal to worldPosition.

#

I am currently successfully making the object have the same rotation as the camera, and follow the camera with an offset

#

now I need to make it rotate around the player.

#

I tried using the ParentConstraint component, but its too stuttery. So I'm back to square one.

latent latch
#

Or what kind of rotation you looking for

#
public static Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 axis, float angle)
{
    Quaternion rotation = Quaternion.AngleAxis(angle, axis);
    return rotation * (point - pivot) + pivot;
}

Forgot they're is no specific Quaternion only RotateAround but this is similar that I use

#

usually mix it with LookAt

slate lark
#

why the player is not translating to ground?

slate lark
carmine iris
#

can someone explain why this is not working

latent latch
#

Im surprised it doesn't throw an error as a zero direction is like imploding into yourself or some thing lol

#

actually, I guess that would just imply no movement since there's no magnitude anyway

crisp folio
#

so I need ground checking in my game to see if you are touching the ground or not. but when I do the ray cast it says that I'm only grounded when I look in a specific place. like if it only checks when I'm looking in a perfect number of degrees. i am very new to coding in unity and i have no knowledge on what culd be the problem. here is a snipet of my code. just ask me if you need everything:

void checkForGround()
{
    Ray ray = new Ray(transform.position, new Vector3(0f, -1.1f, 0f));
    RaycastHit hit;
    Debug.DrawRay(transform.position, new Vector3(0f, -1.1f, 0f), Color.green);

    if(Physics.Raycast(ray, out hit, 1, ~RayLayerMask))
    {
        Debug.Log("grounded " + hit.collider.gameObject.name);
        isGrounded = true;
    }else
    {
        Debug.Log("not grounded");
        isGrounded = false;
    }
}
```(this is run in Update())
latent latch
#

casting usually has problems if it spawns inside of colliders

crisp folio
#

Oh ok I’ll try that. So you mean Line to spawn it above the player?

latent latch
#

it looks like the pivot is at the ground if that's where you're casting from

#

add a few units on the y from the transform position if that's where it's at

hollow mantle
#

hi, i've try to find the problem but i don't find it

upper pilot
#

How can I rotate a collider into a specific Vector2 direction?

#

I want my character to have a "face direction" for interacting with npcs and such.

lethal vigil
#

has anyone had an issue with motion blur or blur in game when running the game at 30fps, when running at 60 the is no blur but of course for a mobile game 30 is better

sly widget
#

Hey, hope someone can help me. I'm having issues with my script as when an enemy is spawned, it won't move - Waypoint controller : https://pastebin.com/eAeS3B5H & EnemyMovement : https://pastebin.com/5WwqTeSH

plain ibex
#

i have a game object that moves with rigidbody2d. I want to when other objects collides with that object: that object mustn't push by other objects

#

how can i do it

somber nacelle
#

if you do not want the object affected by outside forces then it would need to be kinematic

plain ibex
#

thank you very muchh

somber nacelle
#

note that outside forces includes forces like gravity. and it cannot be moved with AddForce

plain ibex
#

i understood 👍

#

i have another problem. i want to use vector3.lerp but it works like its teleporting

#

wall.transform.position = Vector3.Lerp(transform.position, new Vector3(3.03f,-1.08f,0f),4f);

somber nacelle
#

yes, that is teleporting it

plain ibex
somber nacelle
#

your t value is 100% incorrect

#

according to that page i linked, lerping from transform.position to new Vector3(3.03f, -1.08f, 0f), what position will be returned when t is equal to 4?

somber nacelle
#

well no, not just a single axis. it will return the entire Vector3. because your t value is greater than or equal to 1.

plain ibex
#

ah thats true yes but i tried all of them. i made it x>1, 0<x<1 , x<0 but it teleported everytime

somber nacelle
#

you shouldn't just be using a set value for t. did you not read how it works and how you should be using it?

#

although perhaps you want something more like Vector3.MoveTowards if you just want to specify a speed for the third parameter

plain ibex
somber nacelle
#

those methods must be called multiple times in order to work the way you expect, yes

plain ibex
#

so problem was that , thanks again..

glossy gust
#

string p2Name = GameObject.Find("p2Name").GetComponent<P2_NameInput>().input;
p2Text.text = p2Name+", are you ready?";

anything look wrong with this?

#

no errors but p2Name isnt being displayed

plain ibex
#
public void skillButtonClick()
    {
        if (Time.time-lastSkillTime >= 20f || firstSkill)
        {
            skillStartTime = Time.time;
            bringWall = true;
            firstSkill = false;

        }
    }

    private void Update()
    {
        if (bringWall)
        {
            wall.transform.position = Vector3.MoveTowards(wall.transform.position, new Vector3(3.03f, -1.08f, 0f), 0.01f);
        }

        if(Time.time - skillStartTime > 6)
        {
            bringWall = false;
            wall.transform.position = Vector3.MoveTowards(wall.transform.position, new Vector3(3.03f, -9.05f, 0f), 0.01f);
        }
    }```
in this code i want to **finish** "if(Time.time - skillStartTime > 6)" 
and **make** lastSkillTime = Time.time 
**when** "wall.transform.position = Vector3.MoveTowards(wall.transform.position, new Vector3(3.03f, -9.05f, 0f), 0.01f);" **finishes**
#

how can i do?

spring creek
gray mural
gray mural
#

the code that is below this assignment happens just after the position is assigned

#

this is not a coroutine

plain ibex
#

not update

gray mural
#

No?

#

What do you even want to achieve, I don't get the purpose?

plain ibex
gray mural
#

Alright, that doesn't fully explain it

#

Skill button should be activated after buttonCooldown seconds have passed since the skill has ended, right?

#

Then you should probably use coroutines

plain ibex
plain ibex
deep path
#

do you following this tutorial ?

#

How can we get a response from a player input ? Let's find out !

❤️ Support on Patreon : https://www.patreon.com/ValemVR
🔔 Subscribe for more Unity Tutorials : https://www.youtube.com/@ValemTutorials?sub_confirmation=1
🌍 Discord : https://discord.gg/5uhRegs
🐦Twitter : https://twitter.com/valemvr?lang=en
👍 Main Channel : https://www.youtube.com/...

▶ Play video
waxen blade
#

I am trying to give the player the value of a pickup/consumable. It's already on the scene as a prefab, but you pick it up by pressing a key on the keyboard, so there's no colliders. The prefab will have a component called Loot, and in it is a method called PayOut. I want the PayOut method to give the value of the pickup.

When it's time to give the pickup to the player, I want to avoid a giant if statement that looks like:

        if (transform.name == "Coin")
        {
            //Give coin
        }
        else if (transform.name == "Heart")
        {
            //Give heart
        }
        else if (transform.name == "Potion")
        {
            //Give potion
        }

Is there a more efficient way I can do this?

icy prawn
#

you could use a switch statement

desert blade
#

or you could do some form of inheritence to further optimise it like public class Item and have a function called Collect()

icy prawn
#

switch (transform.name)
{
case "Example1":
break;
case "Example2":
break;
default:
break;
}

somber nacelle
#

please do not base logic on gameobject names

icy prawn
#

or what Unscripted said

waxen blade
waxen blade
icy prawn
#

could also do a simple interface where you make a PickupAble with a empty method Pickup() and just make it do whatever it needs to do for certain objects

#

It's a lil bit simpler but not as good. Should do the job though

waxen blade
#

From what I understand, interfaces and inheritance are kind of similar.

glass linden
#

Do you think it is possible to retrieve data from the TikTok API to execute code when a live receives a gift?

waxen blade
#

I need to research both of them some more.

icy prawn
# waxen blade I need to research both of them some more.

https://www.youtube.com/watch?v=MZOrGXk4XFI
Just a nice lil guide for interfaces with some actual examples

📝 C# Basics to Advanced Playlist https://www.youtube.com/playlist?list=PLzDRvYVwl53t2GGC4rV_AmH7vSvSqjVmz
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses​
👍 Learn to make awesome games step-by-step from start to finish.
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle

✅ Let's learn all about Interfaces in C# and how ...

▶ Play video
dense estuary
lethal vigil
#

is there anyway to stop moving objects from looking blurry if my game needs to be set to 30fps

maiden fractal
plain ibex
#

they worked but

#

not interpolate

#

like teleported

#
public void skillButtonClick()
    {
        if (Time.time-lastSkillTime >= 20f || firstSkill)
        {
            firstSkill = false;
            StartCoroutine("SkillStarted");
        }
    }

    IEnumerator SkillStarted()
    {
        while(wall.transform.position.y < -1.08f)
        {
            wall.transform.position = Vector3.Lerp(wall.transform.position, new Vector3(3.03f, -1.08f, 0f), 3f);
        }
        yield return new WaitForSeconds(6f);
        while(wall.transform.position.y > -9.05f)
        {
            wall.transform.position = Vector3.Lerp(wall.transform.position, new Vector3(3.03f, -9.05f, 0f), 4f);
        }
        
    }```
#

here is my code

lethal vigil
arctic plume
#

Would anyone be able to help me with an issue I'm having with my code?

    void Update()
    {
        timer += Time.deltaTime;

        if (timer > interval)
        {
            timer -= interval;
            //Check that someone is actually speaking
            if (currentSpeaker != null && player!=null)
            {
                RaycastHit hit;
                if (Physics.Raycast(player.position, currentSpeaker.position - player.position, out hit, Mathf.Infinity))
                {
                    if (hit.transform == currentSpeaker)
                    {
                        eyeContactTime++;
                    }
                }
                speakingTime++;
                Debug.Log(player + " has spent " + eyeContactTime + " looking at " + currentSpeaker);
            }
        }
    }

It's supposed to measure how long the player spent looking at the active speakers whenever they were speaking, but for some reason it doesn't seem to register it at all and always results in 0
I did get a lot of the code from a Unity forum thread online so I'm not an expert at it

Also it's a VR project so player is set to the Main Camera component of the XR Rig and currentSpeaker is set to the whole model of the NPC that's speaking

maiden fractal
deft pilot
# plain ibex not interpolate

this is probably because you dont have a condition that executes the function on the coroutine, its not really like Update function where it occurs every frame

gray mural
deft pilot
#

ahhh i see

gray mural
#

So what you do is set the wall.transform.position first to (3.03f, -1.08f, 0f), then wait 6 seconds and set it to (3.03f, -9.05f, 0f)

#

Which, yeah, doesn't really smoothly move the wall

plain ibex
plain ibex
leaden yoke
#

I'm struggling to learn c# I watch brackeys taking about variables and conditions and I haven't really learnt anything can someone help I need advice

glossy gust
#

!code

tawny elkBOT
glossy gust
#

I feel like im doing something majorly wrong

somber nacelle
#

the first step for getting help simplifying it is to format it in a way that is actually readable

glossy gust
#

cause code is code

somber nacelle
#

"code is code"

#

you close multiple scopes on a single line like a dozen times. you have loops and if statements nested to oblivion. comments at the end of lines instead of on the line above/below what you are commenting on, a complete lack of white space to divide up different sections of behavior

#

oh and you chose like one of the worst bin sites so there is almost no syntax highlighting making that even more unreadable (though that isn't really a fault of you or your code)

glossy gust
#

I get what you mean by closing multiple scopes at a time to, just did that to save space for importing this into my documentation

somber nacelle
#

unreadable == cannot be read to determine what can be simplified

glossy gust
#

what are typical ways of avoiding using so many nested loops and if statements though

#

I am not aware of other methods

#

if that makes sense

somber nacelle
#

guard statements, breaking logic up into methods, better logic

gray mural
gray mural
#

For instance, this condition you have

if (overlappingColliders.Contains(woodColliders[i]) || overlappingColliders.Contains(groundCollider))
{
    isPlaceable = false;
} 
else 
{ 
    isPlaceable = true;
}

can be written like this

isPlaceable = !(overlappingColliders.Contains(woodColliders[i]) || overlappingColliders.Contains(groundCollider));

or like this

isPlaceable = !overlappingColliders.Contains(woodColliders[i]) && !overlappingColliders.Contains(groundCollider);
vast patio
#

Does someone know how to code the following? Im kinda stuck at this problem, which shouldn't be that difficult...

I want a method GetObject(Transform root, name, depth) in which I want to traverse all childs of root (but max 'depth' times deep) recursivly.
If I find an object with the same name specified in the params, I return it and stop the whole function. If i find nothing I return null.

#
private void IterateOverChild(Transform original, int currentLevel, int maxLevel)
        {
            if (currentLevel > maxLevel) return;
            for (var i = 0; i < original.childCount; i++)
            {
                Debug.Log($"{original.GetChild(i)}"); //Do with child what you need
                IterateOverChild(original.GetChild(i), currentLevel + 1, maxLevel);
            }
        }

Something like this, but I want to return the object I find and leave the whole function, when It has a specific name.

knotty sun
#

so return Transform instead of void and add name as a parameter

icy prawn
#

what Steve said and when you find something, just "return theFoundGameObject" and it should exit the method automatically

vast patio
#

But what if it founds the object at depth 3, than it exits the 3rd function and the ones continues doesnt it?

knotty sun
#
Transform t = IterateOverChild(original.GetChild(i), currentLevel + 1, maxLevel);
if (t != null) return t;
dense estuary
vast patio
# knotty sun ```cs Transform t = IterateOverChild(original.GetChild(i), currentLevel + 1, max...

So like that?

private Transform IterateOverChild(Transform original, int currentLevel, int maxLevel)
    {
        if (currentLevel > maxLevel) return null;
        for (var i = 0; i < original.childCount; i++)
        {
            if (original.GetChild(i).name.Contains("doorAss")) return original.GetChild(i);
            Transform t = IterateOverChild(original.GetChild(i), currentLevel + 1, maxLevel);
            if (t != null) return t;
        }

        return null;
    }
knotty sun
#

best to pass name as a parameter rather than hard coding it but yes

vast patio
#

ok it works from what I see, but cant really wrap my head around it, thank you tho!

gray mural
#

I have read incorrectly

vast patio
#

Yes, lets say I got this hierarchy, I call this function on Door and want DoorAssembly returned, but the hierarchy can vary, the names does not.

plain ibex
gray mural
knotty sun
#

tbh it would be better written as

private Transform IterateOverChild(Transform parent, int maxLevel, string name)
    {
        if (maxLevel < 0) return null;
        foreach (Transform t in parent)
        {
            if (t.name.Contains(name)) return t;
            Transform found = IterateOverChild(t, maxLevel-1, name);
            if (found != null) return found;
        }

        return null;
    }

@vast patio

vast patio
gray mural
#

Doesn't it subtract 1 from maxLevel?

vast patio
#

yea it does

gray mural
#

So if your maxLevel is 3 and your root has 5 children, it'll just stop iterating on the 3rd one

vast patio
#

so you start with high max level and decrease it the further you go down

icy prawn
#

I think maxlevel is how deep he wants to search for i think

vast patio
knotty sun
#

basically maxLevel becomes 'levels left to search'

somber nacelle
#

you need to copy maxLevel decrement it before the loop because otherwise it's decrementing for each iteration of the loop rather than just each depth searched

gray mural
gray mural
vast patio
gray mural
icy prawn
#

btw would there even be a point to limiting how far you want to search other than for performance even though you really would like to find it?

gray mural
vast patio
icy prawn
#

Ow ok, fair enough

knotty sun
gray mural
knotty sun
#

also with recursive methods, one small mistake and you have a stack overflow if they are not limited

tawny elkBOT
vast patio
#

Appreciate the help from all you guys

modern creek
#

Is there any way to search for all gameobjects that contain a certain component?

#

(just in the editor/design time)

#

oh nevermind, just searching for the component name worked

gray mural
carmine iris
#
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;

public class Player : MonoBehaviour
{
    [SerializeField] float moveSpeed = 1f;
    [SerializeField] float rotationSpeed = 1f;
    bool isTilting = false;

    [SerializeField] GameObject stars; 
    [SerializeField] GameObject clouds;

    bool showRocket = false;
    bool canPlayerMove = false;

    Vector2 rawInput;

    async void Start() 
    {
        //hazir ol text
        await Task.Delay(2000);
        showRocket=true;
    }

    void faster()
    {
        Time.timeScale = 20f;
        Time.fixedDeltaTime = Time.timeScale * 0.02f;
    }

    void Update()
    {
        if (showRocket == true)
        {
            transform.position = Vector3.Lerp(transform.position, new Vector3(0f,-3f,0f), moveSpeed * Time.deltaTime);
        }

        if (canPlayerMove != true)
        {
            if (Input.touchCount > 0 || Input.GetMouseButton(0))
            {
                showRocket=false;
                if (Input.mousePosition.x > Screen.width / 2)
                {
                    MoveCharacter(1f);
                    RotateCharacter(1f);
                    isTilting = true;
                }
                else
                {
                    MoveCharacter(-1f);
                    RotateCharacter(-1f);
                    isTilting = true;
                }
            }
            else
            {
                isTilting = false;
            }
        }

        if (!isTilting)
        {
            RotateCharacter(0f);
        }
    }

    void MoveCharacter(float direction)
    {
        Vector3 movement = new Vector3(direction * moveSpeed * Time.deltaTime, 0f, 0f);
        transform.Translate(movement);
    }

    void RotateCharacter(float direction)
    {
        Quaternion targetRotation = Quaternion.Euler(0f, direction * 40f, 0f);
        transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
    }

    IEnumerable Delay(float sec)
    {
        yield return new WaitForSeconds(sec);
    }
}
#

I created a code like this. When I click to left of the screen, the ship going to left and changing x axis. But at the same time Z axis changing too. I did not do anything to Z axis in code why it is changing

glossy gust
#

how do you do SetActive(true); on an object which doesn't have a direct reference, but only a Find("objectName") reference

#

can you get it's parent and then do setactive on the inactive child?

#

or should i just use its components

heavy bone
#

im trying to make code that follows one play er until they shoot their cannon which will switch the camera to follow the projectile and then when the projectile is destroyed it switches to the other player and so on.

#

i dont know the basics of unity but i have some code running that doesnt work

#

how would you guys make code like that?

merry stream
#

is it better to do damage numbers using vfx graph or particles, rather than instantiating, if so how

lean sail
lean sail
glossy gust
#

how would you guys go about making a camera which zooms out to show a wider landscape?

#

i just need to know the methods and I can do the rest

ashen yoke
#

change fov, dolly the camera

dawn nebula
#

So I have this chain sprite asset here. I want to be able to distort it a bit. Wiggle and jiggle with some sort of input. Is there an easy way to do this?

merry stream
fast moon
#

how do I use a past untiy project on github as a boilerplate for future unity projects?

#

I also want to to be able to update it in the future projects

#

something like a fork, but I can't fork my own repositories

maiden fractal
buoyant scroll
#

The type or namespace UI does not exist in the namespace UnityEngine, even though the package is installed.
CS0234, how do I fix this?

somber nacelle
#

is the error only in your IDE or do you see it in the unity console as well?

buoyant scroll
#

Unity console.

somber nacelle
#

are you using assembly definitions

buoyant scroll
#

I don't understand what that means

glossy gust
somber nacelle
#

or rather, in any folder in the path to the file with the error

buoyant scroll
#

No, I don't think so

somber nacelle
#

check

buoyant scroll
#

Alright

#

Like would it usually be in the scripts folder or resources folders or like

somber nacelle
#

check the folders in the direct path to the file with the error. do not bother with any unrelated folders

buoyant scroll
#

No asmdef files

vapid lynx
#

Hey im having a little bit of trouble with something. I want to create a road between two points given an array of vector3's and I can't use splines. How would i go about creating the road thru like a mesh or something idk

somber nacelle
buoyant scroll
#

one moment

#

Assets\Scripts\Assembly-CSharp\UIScript.cs(2,19): error CS0234: The type or namespace name 'UI' does not exist in the namespace 'UnityEngine' (are you missing an assembly reference?)

somber nacelle
#

why do you have a folder called Assembly-CSharp? 🤔

buoyant scroll
#

I in my luxuriest form have no undearest clue.

#

the editor created it.

somber nacelle
#

it most certainly did not

buoyant scroll
#

huh

#

then idk

#

in my project its there

somber nacelle
#

i mean, yeah obviously. but it's concerning that you've got folders named after assemblies. if you move that file directly into the Scripts folder does the issue persist?

buoyant scroll
#

what do you mean

simple egret
#

Searching the internet for it, seems like it's a common thing when ripping existing games

buoyant scroll
#

what file

simple egret
#

For it to put the scripts by compiled assembly name

buoyant scroll
#

yeah, that's because i'm trying to decompile a game from a video and it didn't work

simple egret
#

We cannot help with that as it's against this server's rules

#

You'll have to ask elsewhere

buoyant scroll
#

oh

#

thank y'all for the help though

glossy gust
#

why is this not valid

#

need the child of player1 which is called fightingUI

somber nacelle
#

GameObject does not have a property called fightingUI

#

make your variable type the type of component you actually want to use

merry stream
#

whats the best way to work with shaders in code? say I want to turn on a highlight shader when something is hovered

glossy gust
#

what could I write for that

somber nacelle
#

Canvas also does not have a fightingUI property

raven flare
#

how can i detect whether touch input is inside of a button? it's for a mobile game revive screen where tapping the screen lowers the timer faster, but tapping the button shouldn't also make the timer go down

glossy gust
latent latch
#

could be as simple as appending the angle degrees

cosmic rain
merry stream
cosmic rain
#

There are many ways to implement outlines.

merry stream
#

i made an outline shader

faint hornet
#

Hey everyone. There is a reply in this forum about the very same issue I’m having.

I want to know what the reply means.

Here is the link https://forum.unity.com/threads/unity-2d-multiple-colliders-causing-extreme-lag.643375/

I want prevent extreme lag from rigidbodies colliding, and in the reply he says something like “prevent the physics from overlapping by doing a check before moving”

I have hundreds of rigidbodies colliding and I need to keep them from overlapping (I don’t want them to stack)

cosmic rain
merry stream
cosmic rain
merry stream
#

idk its just a material 🤷‍♂️

cosmic rain
#

It's either a screen space shader or an object based shader?

merry stream
#

object based

#

id assume

cosmic rain
#

Okay, then you'd just add a material with the shader to the object.

merry stream
#

then remove the material when the mouse leaves?

cosmic rain
#

Yep

merry stream
#

how can I set the variables on a shader per instance

#

since when I change the color, all objects with that material get changed

latent latch
merry stream
#

do i just create a new Material witha copy constructor

cosmic rain
cosmic rain
latent latch
cosmic rain
#

Unless you access a sharedMaterial

faint hornet
latent latch
#

isnt the issue of all colliders piling up causing lag

#

so if you prevent overlapping then you only deal with the surrounding colliders

faint hornet
latent latch
#

if you add a force when colliders touch then you only have so many colliders touching each other

latent latch
#

it's a hard issue, but if you are using a lot of units then maybe it's best to use kinematic and object avoidance pathfind algs

faint hornet
faint hornet
latent latch
#

pathfinding using navmesh

#

not sure how updated Unity's is, or if it works with 2D yet, but instead of moving stuff by physics you just pathfind.

#

It's just an option, but seeing that image I don't know why'd you get performance issues

#

it's not a lot of units

slender mirage
#

👋 I'm looking to create a VR Game from scratch, does anyone know of any docs that would help out with detecting the position of the headset / controllers?

faint hornet
# latent latch pathfinding using navmesh

oh ok ill look that up... but i have an infinite boundless world, so navmesh seems overcomplicated..

scan to the end of this video, should i do something like this? https://www.youtube.com/watch?v=SVazwHyfB7g

Lets explore building a self steering ship that can automatically move out of the way of obstacles in it's path. This is a form of steering algorithm which is used to steer a object towards in objective, in our case we'll be using it for obstacle avoidance.

This approach works by casting a number of rays in front of the ship which can detect ob...

▶ Play video
slender mirage
#

Ah ray based movement

latent latch
#

that's a lot of rays per unit though

#

pathfinding avoidance is usually done through checking if other units are on similar paths or similar destination area

faint hornet
latent latch
#

I use A* project for pathfinding with kinematic rbs and it works pretty well as it has it's own character controller

cosmic rain
faint hornet
faint hornet
cosmic rain
#

So they can move independent from the other objects in a group?

cosmic rain
#

It's not like they're stuck together?

faint hornet
cosmic rain
#

Okay, that complicates things. Whatever approach you take, it would be heavy on performance with a large enough amount of these objects.

faint hornet
faint hornet
cosmic rain
#

The only good solution is to convert to dots.

latent latch
#

I feel like kinematic rbs would work here fine and just force stuff from each other

cosmic rain
#

I don't know if it's built with unity, but if it is, I'd assume they use dots/ECS or something similar.

latent latch
#

assuming you're just moving each unit towards the player

cosmic rain
faint hornet
latent latch
cosmic rain
faint hornet
latent latch
#

like, vampires collisional stuff is very loose and janky

#

it just slowly displaced units around each other

cosmic rain
faint hornet
faint hornet
cosmic rain
latent latch
#

yeah, it's not perfect as it would cause some erratic movement, but really similar behavior to that specific game

faint hornet
cosmic rain
#

Entity component system.

faint hornet
cosmic rain
#

Specifically when the lag occurs.

#

I'd also use a profiler to make sure you're interpreting the lag cause correctly.

faint hornet
#

@cosmic rain @latent latch objviously i should use object pooling to reduce some issues, but maybe thats why its cause so much lag also? physics calcs AND instantiations ? ( btw, when running the BUILD of the game, lag happens a bit later, like at 400 objs)

latent latch
#

object pool is useful when instantiation/destroying

#

more of an issue of calcs here

cosmic rain
faint hornet
latent latch
#

rb's are just not the cheapest for these types of games

cosmic rain
faint hornet
cosmic rain
cosmic rain
cosmic rain
faint hornet
cosmic rain
#

Do you have some logic in on collision/trigger enter or stay?

faint hornet
cosmic rain
#

Okay

faint hornet
cosmic rain
#

Well, the main issue is that the physics loop is snowballing itself

#

You see there are 333 fixed updates in that frame.

#

Maybe reducing the fixed time step would help prevent it

faint hornet
faint hornet
cosmic rain
#

No. If interpolation is working correctly. It might make collisions less precise though

cosmic rain
faint hornet
latent latch
#

Not a bad idea, I should really mess with my timesteps too

latent latch
#

lol

#

why is the default that low

cosmic rain
#

Why was it so low?

#

It's not the default...notlikethis

glossy gust
#

!code

tawny elkBOT
cosmic rain
#

If you try making 1000 fixed updates in one second of course it will lag and snowball. Wtf lol

faint hornet
silk narwhal
# faint hornet the fixed update for each enemy

one thing would be making new calculations on update only if a given object is within some distance and if the player moved any amount. Perhaps ditching the update() entirely for this and implementing some global callback when a player moves some distance over time, and re-calculating only then instead could improve?

latent latch
#

probably updating faster than your refresh rate

faint hornet
#

now i have this many enemies with no noticable lag

cosmic rain
faint hornet
cosmic rain
latent latch
#

.02 is the actual value

cosmic rain
#

You can make it bigger and it might help a bit more

latent latch
#

.04 should be fine

faint hornet
# latent latch .04 should be fine

i changed it to .04 but now the bullets don't look smooth when they make contact. for example the bullet reaches an enemy and destroys itself, so most of the time it disapears before reaching the enemy... visual problem, does,t change performance

latent latch
#

try continuous discreet

faint hornet
latent latch
#

mess around with the different mods usually

#

yeah, projectiles can be somewhat problematic at higher steps

#

can always just physics query it yourself is an option. It's a balance of projectiles vs enemies

#

assuming enemies don't move that quickly

faint hornet
faint hornet
latent latch
#

if you want to do it by physics query then you'd do it via update but this requires you writing the interpolation too

#

just an option, but stick with a timestep that works for you right now

merry stream
#

can only one component with OnMouseEnter be present on a gameobject? it seems like the 2nd script doesnt take the callbacks

steep patrol
#

Hello, does anyone know of what type of coding it is when you calculate out a timetable of events all at once, and then try to add/edit an event that makes you have to recalculate the whole chain of events? In this particular case, I'm trying to build a tool that helps build a visual timetable of train departure/arrivals, while calculating the station crafting and showing the current storage of each station at each quarter-second of time, and any time a train changes it's departure or arrival time or a train is added/removed it has to recalculate all the figures all over.

latent latch
#

Something like an observer pattern?

#

Such that if something changes, then you invoke a full recalculation of everything if that's what you're asking

silk narwhal
faint hornet
long forge
#

Looking for help fixing an issue. Not sure if this is the right place but cant find anything useful online

#

My character is falling through the ground for a split second and overall just jittery/shaky animations. I’ve included much of the code in the video. Any help is greatly appreciated.

latent latch
#

post code to bin

#

!code

tawny elkBOT
fervent coyote
#

Hi there;
I'm trying to make a basic circle that would output as a direction for Raycasts;

Making a unitCir: float unitCir = (360 * Mathf.Deg2Rad * (Mathf.PI * 0.1f)) * (i / maxSpawned) + Random.Range(-0.25f, 0.25f);
(In the code, the Random.Range is supposed to be a random additional degrees of angles)
Position: transform.position + new Vector3(Mathf.Cos(unitCir) * radius, 50, Mathf.Sin(unitCir) * radius)

Now, you would be saying "Why not use Random.InsideUnitCircle? And I was using that, but I realized that I wanted the absolute EDGE of a circle, and also wanted to have more control over it, as well as use it later on for directions

But right now, it doesn't seem to work correctly... Can anyone help?

silk narwhal
latent latch
#

I seem to hardly touch radians and just do stuff like a rotation + magnitude or vectors with a range of positions like saksiu's example

silk narwhal
#

yup, when I can I just let the engine handle those pesky radians and play around with Vectors, few videos deep, and still can't quite understand them.

I believe using the second thing I proposed, perhaps then normalizing the resulting vector (to ensure magnitude) and mutliplying by whatever you need (force) should do the trick

fervent coyote
#

I was really hoping though for it to be a perfect circle...

cyan hornet
#

Why does my Player Input not have this Jump CallbackContext ???

silk narwhal
cyan hornet
#

( mine is the white themed Unity )

quartz folio
latent latch
fervent coyote
#

Oh, I figured out
degree = Random.Range(-360, 360)
unitCircle = (degree * Mathf.Deg2Rad)
Vector3(MathF.Sin(unitCircle), 0, MathF.Cos(unitCircle))

#

God I love desmos for prototyping

#

Desmos is a life saver for math

faint hornet
silk narwhal
#

you are seeing it above I believe

faint hornet
# fervent coyote Wikipedia

I have a different solution that also works. You just choose a pivot point and another point 1 unit above it use both of those to rotate x degrees. (0,360)

fleet gorge
#

Recently I found that my player was jittering as my camera movement is in Update, but the physics update happens in FixedUpdate

I changed physics simulation to happen in Update and now everything is smooth but are there any real downsides to this?

#

Will a person on 60hz vs 165hz have different physics?

latent latch
#

camera movement usually late update

fleet gorge
#

Ohh

#

How is lateupdate different from script execution order?

faint hornet
latent latch
faint hornet
fleet gorge
#

I'll need to experiment with it

#

I just want the updates to happen as frequently as possible so it feels smooth

latent latch
#

cinamachine has some more options

fleet gorge
#

I'm making a platformer game so I probably won't use cinemachine 😅

latent latch
#

it's pretty much standard on all projects now

#

every unity template comes with it

faint hornet
latent latch
#

(well, those with controllers added)

fleet gorge
#

It's most likely physics related; When I change player's position in Update it's smooth, but falling is still jittery

faint hornet
fleet gorge
#

After making physics based on Update then everything became smooth

#

Is LateUpdate as frequent as Update?

#

Or is it as frequent as FixedUpdate

faint hornet
fleet gorge
#

I'm using rigidbody3d and it's choppy

#

It's a 2.5d platformer so I used a 3d scene

faint hornet
fleet gorge
#

Constraining the player on the z axis

fleet gorge
faint hornet
faint hornet
fleet gorge
#

Initially I was using interpolate with rb.MovePosition in FixedUpdate

#

Very choppy

#

This was when I still based physics in FixedUpdate

lean sail
fleet gorge
#

Idk I feel like cinemachine is overkill

faint hornet
fleet gorge
#

The player is choppy but the camera is smooth

faint hornet
lean sail
fleet gorge
faint hornet
fleet gorge
#

Only rigidbody methods

#

The player is only moved in FixedUpdate by rb.moveposition and rb.addforce

faint hornet
faint hornet
fleet gorge
#

Yep

faint hornet
faint hornet
# fleet gorge Yep

Have you tried removing your own gravity just to test it out? Comment it out and add gravity forces in the inspector of the rigid body

faint hornet
# fleet gorge Yep

I’m sure there is a way to make it work with your own gravity and the use of rigid bodies but I think that would only be beneficial if you had some kind of interesting gravity stuff like black holes etc..

What type of artificial gravity are you trying to achieve ?

fleet gorge
#

allowing you to walk on walls

runic nimbus
slim aspen
#

I have a standard camera controller that rotates the camera using x and y values controlled by inputs.

How do I modify those values using math to make it look at an object automatically?

LookAt() is something I want to avoid, because after something happens (eg. first-person in-game NPC diaglog/cutscene), the camera will simply snap back to the x and y values that were set before it disabled in favor of said "something"

slim aspen
#

No, the problem with LookAt is it's not the camera controllee that is moving:

  1. Look at 270° degrees using mouse (camera controller)
  2. NPC calls you from 90°
  3. Camera controller is still looking at 270° before being disabled
  4. LookAt can finally overwrite the rotation, making the camera "look" at NPC at 90°
  5. Cutscene ends and the LookAt script disables
  6. The Camera controller re-enables and snaps player back to 270°
#

this is the scenario I'm trying to avoid

latent latch
#

oh wait those are the vector versions

#

Need the quaternions

#

yeah, basically you have Sleerp or RotateTowards in your late update constantly reading at the current target rotation

#

you can override it and it will just pick up at that rotation (but there's a different between these two methods, Slerp is specific timing while RotateTowards is a constant speed)

royal gulch
#

What are the best practices for instantiating prefabs during runtime?

For my previous project, I made a PrefabCache class and stuck it on an empty gameobject and added all my prefabs as public serializefield variables in that class so that other scripts can access the prefab they need.

After reviewing my project based on what I've learned, this method seems wrong. Is using Resource.Load the better way to grab and instantiate prefabs during runtime, or is there some design pattern I can implement?

latent latch
#

prefabs and SOs (mostly any constructed asset instance) I like to throw IDs on and stick em into lookup tables

royal gulch
#

when creating a lookup table, is there a specific unity feature that I should look into using, or is it just a plain dictionary data structure?

latent latch
#

Dictionaries solve everything

#

The reasons I do it this way is for serialization purposes (loading, saving, networking), such that I do more dependency injection than having the assets constructed

royal gulch
#

Okay, thank you. I will try this approach in my next project

desert jackal
#

I'm stuck. Trying to snap to ground, but it only works when I don't specify probeDistance in Physics.Raycast.
When I specify probeDistance [ if (!Physics.Raycast(body.position, Vector3.down, out RaycastHit hit, probeDistance)) ], it doesn't detect ground, no matter what distance I use.

plain ibex
#

my unity crashes when i click a button how can i detect the reason

#

its about code

latent latch
dawn nebula
#

So I have a 0 to 1 value. I want to pick 2 times during a day (like 6am and 2pm) and be able to lerp between them using this number. Any tips?

mellow sigil
#

Use a 24-hour clock and lerp like you'd normally do. Mathf.Lerp(6, 14, t)

plain ibex
#
while(elapsedTime < 2f) {
                foreach (GameObject aE in activeEnemies)
                {
                    aE.transform.localScale = Vector3.Lerp(aE.transform.localScale, new Vector3(1.5f, 1.5f, 1f), (elapsedTime * 0.5f));
                }
                elapsedTime += Time.deltaTime;
           }```
#

lerp doesnt work

#

its changing but not smooth

#

not interpolate

faint hornet
#

can someone tell me why task is spawning all my enemies at the same time instead of in intervals?
I figured out that it works correctly when i put the local varable 'spawninterval' outside of it's scope but not as a local?? so confused

async Task StartRally()
  {
    isRallyActive = true;
    float elapsedTime = 0f;
    float spawnInterval = 0f;  <========================= NOT WORKING AS A LOCAL VARIABLE

    while (elapsedTime <= 120f)
    {
      elapsedTime += Time.deltaTime;
      if (spawnsPerMin == 0 || !isRallyActive) return;

      if (spawnInterval == 0f)
      {
        SpawnEnemyGroup();
      }

      spawnInterval += Time.deltaTime;
      spawnInterval = Mathf.Clamp(elap, 0f, rate);

      if (spawnInterval >= rate) spawnInterval = 0f;

      await Task.Yield();
    }
  }

cosmic rain
# plain ibex not interpolate

Because you're using lerp incorrectly. Check the docs to understand what the third parameter is and what value it's supposed to have.

cosmic rain
plain ibex
#

so i increased third parameter to 1f

#

with while

#

but why didnt work i dont understand

faint hornet
cosmic rain
faint hornet
# cosmic rain Well, try calculating the value that the third parameter has every frame with yo...

so i shoudl do it like this?

async Task StartRally()
  {
    isRallyActive = true;
    float elapsedTime = 0f;
    float spawnInterval = 0f;  <========================= NOT WORKING AS A LOCAL VARIABLE

    while (elapsedTime <= 120f)
    {
      elapsedTime += Time.deltaTime;
      if (spawnsPerMin == 0 || !isRallyActive) return;

      if (spawnInterval == 0f)
      {
        SpawnEnemyGroup();
      }

      spawnInterval += Time.deltaTime;
      spawnInterval = Mathf.Clamp(elap, 0f, rate);

      if (spawnInterval >= rate) spawnInterval = 0f;

       yield return null;
    }
    await Task.Yield();
  }
cosmic rain
faint hornet
cosmic rain
faint hornet
cosmic rain
faint hornet
cosmic rain
#

Does it have a different value when defined outside the task?

faint hornet
cosmic rain
#

Ah, nvm was looking at a different variable.

faint hornet
#

wait, ill simplify the code by removing redundant code. 1 sec

faint hornet
# cosmic rain Why does it have a value of 0?
float spawnInterval = 0f; <================== This works here.
async Task StartRally()
  {
    isRallyActive = true;
    float elapsedTime = 0f;
    float spawnInterval = 0f;  <========================= not working here.

    while (elapsedTime <= 120f)
    {
      elapsedTime += Time.deltaTime;
      spawnInterval += Time.deltaTime;
      spawnInterval = Mathf.Clamp(spawnInterval , 0f, rate);

      if (spawnInterval >= rate) spawnInterval = 0f;

      await Task.Yield();
    }
  }
faint hornet
#

how did i not see that

plain ibex
#

interesting

faint hornet
cosmic rain
cosmic rain
faint hornet
faint hornet
mellow sigil
latent latch
#

if you're not using a coroutine, why are you using a while loop

faint hornet
cosmic rain
faint hornet
cosmic rain
#

And test of course

faint hornet
# cosmic rain Can you replace it with a debug log and share the full code?

this is the full code that doesn't work

async Task StartRally()
  {
    isRallyActive = true;
    float elapsedTime = 0f; 
    float spawnInterval = 0f; <++++++++++++++++++++++++

    while (elapsedTime <= 120f)
    {
      elapsedTime += Time.deltaTime;
      if (spawnsPerMin == 0 || !isRallyActive) return;

      if (spawnInterval == 0f)
      {
        SpawnEnemyGroup();
      }

      spawnInterval += Time.deltaTime;
      spawnInterval = Mathf.Clamp(elap, 0f, rate);

      if (spawnInterval >= rate) spawnInterval = 0f;

      await Task.Yield();
    }
  }

This is the full code that DOES work

float spawnInterval = 0f; < =====================

async Task StartRally()
  {
    isRallyActive = true;
    float elapsedTime = 0f;
    

    while (elapsedTime <= 120f)
    {
      elapsedTime += Time.deltaTime;
      if (spawnsPerMin == 0 || !isRallyActive) return;

      if (spawnInterval == 0f)
      {
        SpawnEnemyGroup();
      }

      spawnInterval += Time.deltaTime;
      spawnInterval = Mathf.Clamp(elap, 0f, rate);

      if (spawnInterval >= rate) spawnInterval = 0f;

      await Task.Yield();
    }
  }
plain ibex
#

in a coroutine

latent latch
#

ya need to yield then

plain ibex
#

return null ?

faint hornet
faint hornet
latent latch
#

replying @plain ibex
But yes, return null as it'll go back into it next frame

cosmic rain
#

And where is the debug log?

plain ibex
faint hornet
#

it's fixed. thank you @cosmic rain i knew it was something stupid lol most of my errors are like that haha

latent latch
#

if it's a coroutine inanother coroutine then that's somethign to consider

plain ibex
# latent latch looks fine to me honestly but I need to see the full code
private IEnumerator SkillLerp(float time)
    {
        float elapsedTime = 0;
        if(PlayerPrefs.GetInt("AticiID") == 0)
        {
            while (elapsedTime < time) //wall gelis
            {
                wall.transform.position = Vector3.Lerp(new Vector3(3.03f, -9.05f, 0f), new Vector3(3.03f, -1.08f, 0f), (elapsedTime / time));
                elapsedTime += Time.deltaTime;
                yield return null;
            }

            yield return new WaitForSeconds(2);
            elapsedTime = 0;
            while (elapsedTime < time) //wall gidis
            {
                wall.transform.position = Vector3.Lerp(new Vector3(3.03f, -1.08f, 0f), new Vector3(3.03f, -9.05f, 0f), (elapsedTime / time));
                elapsedTime += Time.deltaTime;
                yield return null;
            }
        }
        else if (PlayerPrefs.GetInt("AticiID") == 1)
        {
           while(elapsedTime < 10f) {
                foreach (GameObject aE in activeEnemies)
                {
                    aE.transform.localScale = Vector3.Lerp(aE.transform.localScale, new Vector3(1.5f, 1.5f, 1f), (elapsedTime/10f));
                }
                elapsedTime += Time.deltaTime;
                yield return null;
           }

            while (elapsedTime < time) 
            {
                elapsedTime += Time.deltaTime;
                yield return null;
            }

            activeEnemies = GameObject.FindGameObjectsWithTag("Enemy"); //eski scalea geri dondurme
            foreach (GameObject aEd in activeEnemies)
            {
                aEd.transform.localScale = new Vector3(1f, 1f, 1f);
                other.scaleSkill = false;
            }

        }
        lastSkillTime = Time.time;
    }```
latent latch
#

what's the point of everything below what you're lerping

#

keep it simple for now, and try to get that piece of code from before working

#

then continue adding more logic

plain ibex
cosmic rain
plain ibex
plain ibex
#

not smooth

#

it changes directly

#

third parameter is true

#

im sure

cosmic rain
faint hornet
#

@cosmic rain do you know why this isn't working?
so the game isn't freezing up or anthing, it's currently just not running the RallyCountdown Function. when it gets to the while loop nothing executes after that.

async Task RallyCountdown(float duration)
  {
    float elapsedTime = 0f;
    while (elapsedTime < duration)
    {
      currentRally.CountDownText(duration - elapsedTime);
      elapsedTime += Time.deltaTime;
      elapsedTime = Mathf.Clamp(elapsedTime, 0f, duration);

      if (elapsedTime > duration) return;
      await Task.Yield();
    }

  }

  async Task StartRally(float countdownDuration)
  {
    isRallyActive = true;

    await RallyCountdown(countdownDuration);

    float elapsedTime = 0f;
    float spawnInterval = 0f;
    while (elapsedTime <= 120f)
    {
      elapsedTime += Time.deltaTime;
      if (spawnsPerMin == 0 || !isRallyActive) return;

      if (spawnInterval == 0f)
      {
        SpawnEnemyGroup();
      }

      spawnInterval += Time.deltaTime;
      spawnInterval = Mathf.Clamp(spawnInterval, 0f, rate);

      if (spawnInterval >= rate) spawnInterval = 0f;

      await Task.Yield();
    }
  }
cosmic rain
faint hornet
#

also no errors are occuring

faint hornet
cosmic rain
plain ibex
faint hornet
cosmic rain
cosmic rain
plain ibex
quartz folio
plain ibex
#

not directly scaling too

#

omg i did it but how i dont know

#

haha

merry stream
#

when implenting the builder pattern, is it better to create a seperate class "xBuilder" or just make all the methods in the class itself

thin aurora
#

otherwise you just have some variant of a fluent api

#

The point is that the builder exposes specific functions, and after building you will have a class that doesn't expose any of these type of methods

merry stream
thin aurora
#

It's what i did

#

Then the builder maps the variables into the class through the constructor

merry stream
#

can you give me an example?

thin aurora
#

1 sec

#

I'll share mine, but I have to strip it a bit

#

In my case I could also add an internal constructor to ScheduledEvent so nobody can manually create one, but you need to specify all the types anyway

merry stream
#

ive never used sealed or internal, what do those do again?

thin aurora
#

I don't think Unity supports required keyword on properties yet so you should probably make a constructor instead

thin aurora
#

usage:

var schedule = ScheduledEventBuilder.Create<ServerDataFetchJob>(nameof(ServerDataFetchJob))
    .StartImmediatley()
    .WithRetry(3, TimeSpan.FromSeconds(5))
    .Build();
merry stream
#

if I have everything in the base assembly, does internal not change much?

#

should I avoid having everything in that main assembly?

latent latch
#

pfft sealed and im over here making all my methods virtual and protected just in case

quartz folio
#

sealed does give extremely minor performance boosts 😉

thin aurora
#

C# should enforce sealed by default

thin aurora
#

I wrote this code in a separate project so it does affect it in my case

#

This is a scheduler system so it's more organising to put this in a separate project.Scheduler project for me

#

Also clears up how much can actually be modified by outside sources

wild warren
#

in unity i fetch back users profile picture from a url, then download it and turn it into texture to display it and assign it to a raw image, but getting back this texture takes alot of the devices ram, especally in IOS and makes the ap crash, what should i do to reduce the size of the texture ??

knotty sun
tawny elkBOT
wild warren
#

i'm calling it 3 times because i have three diffrent raw image which i want to take this texture

#

and the code for crop texture is for making all the images square

knotty sun
#

SO you are taking one Texture and producing 3 duplicates

wild warren
#

yes

knotty sun
#

you only need to do it once and then apply the resulting Texture where it is needed

wild warren
#

and thats what i'm doing i get back the texture once in start and giving the result to 3 raw images to be displayed in three places

knotty sun
#

no, that is not what you are doing
you take one texture from the web and make 3 copies of it when you don't need to

gaunt nexus
#

how do i add an element to an array
without doing array[x] = element
like just add it to the end

#

because i wanna make a spawn limit to my enemy spawner

#

and wanna add the enemies to an array

knotty sun
gaunt nexus
#

well time to learn a new thing

merry stream
#

a list is just an array with fancy methods

wild warren
gaunt nexus
#

how do i fix that

latent latch
#

If you destroy a game object you need to still remove it from the list

gaunt nexus
#

i thought that would happen automatticly

latent latch
#

Either by using Remove, or by setting the index null, but unless you're dealing with fixed capacity you should just Remove

gaunt nexus
#

how am i gonna remove tho

latent latch
#

Ideally what you want to do is first remove it from the list and then destroy it.

gaunt nexus
#

idk how to do that 😵‍💫

#

i have this in 1 script

#

but when i tried this in another one

#

it said object refrence not set to insttance of an object

somber nacelle
#

most likely your spawner variable is null

gaunt nexus
#

how can i be so foolish 🤦‍♂️

plain ibex
#
public class BalletScript : MonoBehaviour{
[SerializeField] Enemies enemies;
private GameObject[] activeEnemies;
private bool firstSkill;
private float lastSkillTime;

if (Time.time - lastSkillTime >= 20f || firstSkill){
            {
                other.slowEnemies = true;
                enemies.enemySpeed /= 2;
                StartCoroutine(SkillLerp(6f));
            }
firstSkill = false;
}

private IEnumerator SkillLerp(float time)
    {
activeEnemies = GameObject.FindGameObjectsWithTag("Enemy");
            enemies.enemySpeed = 2;
            foreach (GameObject aEs in activeEnemies)
            {
                enemies.enemySpeed = 2f;
            }
            yield return new WaitForSeconds(6f);
            activeEnemies = GameObject.FindGameObjectsWithTag("Enemy");
            enemies.enemySpeed=4f;
            foreach (GameObject aEs in activeEnemies)
            {
                enemies.enemySpeed=4f;
            }
        }
        lastSkillTime = Time.time;```
#
public class Enemies : MonoBehaviour
{
    public float enemySpeed = 4f; }```
#

it is not changing enemySpeed

mellow sigil
#
foreach (GameObject aEs in activeEnemies)
{
    enemies.enemySpeed = 2f;
}

These loops make no sense

#

It loops through activeEnemies, completely ignores them, and sets an unrelated variable's value every iteration

#

Do the objects with the Enemy tag have the Enemies component?

plain ibex
#

so it must work

#

idk why it isnt working

mellow sigil
#

What makes you think that enemies.enemySpeed is in any way related to activeEnemies?

plain ibex
#

why it isnt working too

mellow sigil
#

Yes, and it changes a completely unrelated variable

plain ibex
#

but it doesnt

mellow sigil
#

you are wrong

somber nacelle
plain ibex
somber nacelle
#

and your Enemies.enemySpeed variable appears to be entirely unrelated to any of this

#

show me a single line where you actually use its value

plain ibex
#

rb.velocity = new Vector2(7.75f - transform.position.x, randomTowerY - transform.position.y).normalized * enemySpeed;

mellow sigil
#

enemies.enemySpeed has nothing to do with the active enemies. Changing it won't change the speed of active enemies

somber nacelle
plain ibex
mellow sigil
#

Active enemies are in variable activeEnemies and each individual enemy is in the variable aEs. Neither of those has any link to the enemies variable.

plain ibex
#
public class Enemies : MonoBehaviour
{
    public float enemySpeed = 4f;
    private Rigidbody2D rb;
    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        rb.velocity = new Vector2(7.75f - transform.position.x, randomTowerY - transform.position.y).normalized * enemySpeed; } } ```
somber nacelle
#

is that the full code

plain ibex
#

theyre about collider etc.

somber nacelle
#

if you are going to continue to not provide the full context, then don't be surprised when you don't get the help you are seeking

plain ibex
#
public class Enemies : MonoBehaviour
{
    public int enemyHealth;
    [SerializeField] private BalletScript balletScript;
    [SerializeField] private GameObject balletObject;
    public float enemySpeed = 4f;
    private Rigidbody2D rb;
    private float randomTowerY;
    private void Start()
    {
        randomTowerY = Random.Range(1.85f, -3f); 
        rb = GetComponent<Rigidbody2D>();
        rb.velocity = new Vector2(7.75f - transform.position.x, randomTowerY - transform.position.y).normalized * enemySpeed;
    }
    public void SpawnAndConfigurePrefab()
    {
        BalletScript instance = Instantiate(balletScript);
        instance.Initialise(balletObject);
    }


    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.CompareTag("Tower"))
        {
            Destroy(gameObject);
        }
        if (collision.collider.CompareTag("Ballet"))
        {
            Destroy(collision.collider.gameObject);
            enemyHealth -= 60;
        }
        if (collision.collider.CompareTag("Wall"))
        {
            Destroy(gameObject);
        }
    }

    private void Update()
    {
        if (enemyHealth <= 0)
        {
            Destroy(gameObject);
        }
    }

    private void OnBecameInvisible()
    {
        Destroy(gameObject);
    }
}
somber nacelle
#

I see that Enemies spawns the BalletScript object. but BalletScript modifies the Enemies.enemySpeed variable. are these components perhaps on the same object?

plain ibex
#

enemies script in enemies prefab

somber nacelle
#

well something is fucky here that you aren't showing. but you also only assign to velocity a single time, never after the enemySpeed variable has been updated

somber nacelle
# plain ibex its the full code.

it's obviously not all of the related code considering you never show where any of the enemy objects are spawned, it's also not the full context because you also don't show what is assigned to the enemies variable on BalletScript (which you also haven't shown the full code for)

somber nacelle
plain ibex
#

BalletScript

knotty sun
#

!code

tawny elkBOT
plain ibex
somber nacelle
#

show where any of the enemy objects are spawned

what is assigned to the enemies variable on BalletScript

plain ibex
# somber nacelle > show where any of the enemy objects are spawned > what is assigned to the en...

1:

public class Other : MonoBehaviour
{
    [SerializeField] GameObject[] randomEnemyObject;
    Vector3 randEnemySpawnLoc;
    public bool scaleSkill, slowEnemies;
    
    private void Start()
    {
        scaleSkill = false;
        InvokeRepeating("randomEnemySpawn", 3f, 2f);
    }
    private void randomEnemySpawn()
    {
        randEnemySpawnLoc = new Vector3(-10.88f, Random.Range(-5f, 5f), 0f);
        GameObject lastEnemy = Instantiate(randomEnemyObject[Random.Range(0, randomEnemyObject.Length)], randEnemySpawnLoc,Quaternion.identity);
        if (scaleSkill)
        {
            lastEnemy.transform.localScale = new Vector3(1.6f, 1.6f, 1f);
        }
    }
}```
2: it assigned to enemies script that in one of prefabs (i have 3 different enemy prefab but all of them have enemies script)
somber nacelle
#

so you change it on one of the prefabs and expect it to affect all of them? and also you expect it to affect the instances in the scene that are now entirely unrelated to that one prefab?

plain ibex
#

i think so because all of them have same script

somber nacelle
#

again, that is incorrect

#

you can't change a variable on the prefab and expect every instance of the component that variable is on to also change. if you want all of them to have the same speed at all times, you could make the variable static. then make sure to update the velocity each time you change the variable

#

of course you should probably also learn the difference between static and instance members before you do that

knotty sun
karmic flame
#

Hey there! I've been facing an issue with my Unity project. I installed 'Microsoft.ML.OnnxRuntime', 'Microsoft.ML', and their related packages via NuGet Package Manager in VS Code. However, whenever I reopen my Unity project, the .csproj file seems to revert back to a state where these packages weren't included. Any advice on how to ensure these package references persist across sessions? Thanks

chilly surge
knotty sun
chilly surge
#

You can either manually install NuGet packages by extracting the dll and putting them in your project assets, or use a NuGet integration for Unity.

karmic flame
#

I will try that so
first: i just need to manaully download a Microsoft.ML.OnnxRuntime.dll and
second: then place it in plugin folder then
third: download the Microsoft.ML.OnnxRuntime again from Nuget Package manager inthe vs code?

chilly surge
#

You don't need to do the third.

karmic flame
#

Okay thanks!! Lemme try it!!

chilly surge
#

When you put a dll in Unity, it regenerates .csproj (or at least it should, if it doesn't then you can do it manually) to make it work.

rain minnow
nocturne wyvern
#

Hello, I'm testing firebase authentication.

Now when I try to login it says first

LoginFailed : An internal error has occurred.

then I call the method again and it already writes

LoginFailed : We have blocked all requests from this device due to unusual activity. Try again later.

Does anyone have any ideas on how to fix it? I'm testing on a laptop

long hare
#

why sometimes while the player is wall sliding he get stuck to the wall ? (is it the script issue or the collider?)

#

I didnt find any issue with the colliders

deft timber
trim schooner
glossy gust
#

I made a grid lock but it isn't working anymore despite the logic and code seeming all perfect

#

I believe the issue came after I mixed the UIs and scene elements, but I cleared the parents and the grid lock is still not working

somber nacelle
glossy gust
#

this script generates the grid, the tags are applied correctly

#

the boundary collider in this script is what I want to check, it has been referenced correctly in the inspector

#

if you need more context ill give it, I will go through any troubleshooting tips. Thanks 🙏

leaden yoke
#

is visual studio code better or visual studio? using it to doing in c# in for unity

chilly surge
#

Both are fine, but if you are not familiar with Unity/development in general, VS is recommended because most tutorials online use VS.

latent latch
#

I use both

#

vs for the tools, debugger, ect. VS code for the glorified notepad

chilly surge
#

I use VS Code exclusively, it also has debugger and what not.

latent latch
#

oh huh I thought that was exclusive to vs

chilly surge
#

Nope, a lot of people seem to have the impression that VS Code is bare bone and has nothing. It has language server so intellisense/autocomplete/diagnostics/etc, debugging works and all the things you expect with debugging like breakpoints/viewing variable values/etc.

#

One of the engineers in the C# language design team who frequents the C# Discord server, works with VS Code for developing the language too.

latent latch
#

it eats 5 less gigs of my mem that's for sure

chilly surge
#

Yeah and it's nice that VS Code opens instantly. Whenever I accidentally click "open in VS" instead of "open in VS Code" I just have to roll my eyes and wait for VS to slowly load before I can even close it.

latent latch
#

I just use it for HLSL and some OpenGL stuff but ill probably look into it more eventually since I heard the unity support has been improved since

chilly surge
#

Although for how much I enjoy VS Code personally, for anyone that asks the question "what should I use," I will always recommend VS. VS is just generally much nicer for beginners that need hand holding, and especially almost all the tutorials online are written assuming you use VS.

spice briar
#

hey everyone, so im making an FPS character controller using CharacterController
it seems like the ground check is extremely inconsistent, even on a terrain collider its unusable.

#

it even turns to false when im just standing still. any idea why this could be happening?

karmic flame
#

so hey i just solve the error , i was having about nuget packages , using visual code community package installer, but now i have a problem everytime i run my game unity crashes

spring creek
tawny elkBOT
void ferry
#

Hello, I am currently trying to change the Rect Transform dynamically at runtime depending on my element count. Can I somehow limit the max transform height? I want to match the size with the elements.

deft timber
#

layout groups + content size fitter @void ferry

#

and layout element

glossy gust
cyan hornet
dull glade
#

I really getting pissed at unity, for some reason my public var doesn't show up in the inspector no matter what I do!?

dull glade
#

Its an animation curve

fringe ridge
#

is animation curve serializable?

dull glade
#

yes

fringe ridge
#

i don't think it is

#

okay, yeah, maybe it is

dull glade
#

Ok I worked it I needed to be in debug view, thanks a lot lunity

cyan hornet
# fringe ridge First of all, where do you call jump?

I added Jump(); in the Update... and now I get this:
Assets\Scripts\PlayerController.cs(35,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'context' of 'PlayerController.Jump(InputAction.CallbackContext)'

#

I got this Input Action here inside of my Player Capsule though so that should be it