#archived-code-general

1 messages Β· Page 347 of 1

dusky lake
#

Is the debug.log in there ever triggered?

rigid island
#

also where is your console window and why is it hidden

clear siren
#

this is the paddle

rigid island
#

show inspector for goal n ball

clear siren
#

the tut

#

basically i started yesterday just learning of other tuts on different subjects

rigid island
#

pong in 6 minutes.. lord..

#

and thought you exactly nothing

#

not a fan of BMo videos.

rigid island
clear siren
clear siren
#

Oh

#

I'm dumb

#

Ball

#

Goal

rigid island
spring creek
rigid island
#

also this ^

clear siren
#

I just started ok πŸ™πŸΌ

rigid island
#

maybe you should start with the essentials pathways

#

it wil teach you how to navigate the editor

maiden heath
rigid island
maiden heath
#

isnt it case sensitive

rigid island
#

no

maiden heath
#

oh nvm then

clear siren
#

Would a screen record be good?

rigid island
#

tecchnially they need to match but afaik newer unity versions don't mind

spring creek
clear siren
#

I'll js screenshot

dusky lake
clear siren
#

There's two goals

#

so what happened is until i added the code for it to return it was fine

maiden heath
#

is this what you mean?

#

i cant make them protected because then i get an error when i try to call them in CombatManager

dusky lake
#
            Debug.Log("player1scored...");

like that

clear siren
#

ill check

maiden heath
# clear siren ill check

unrelated but you should organize your project more, its a hell of a mess right now and thats a bad practice

#
  • also your scripts
#

better to get used to it from now so it can stick with you later down the line

clear siren
#

tag ball is not defined

#

heres the ball code

#

public class goal : MonoBehaviour
{
public bool isplayer1goal;

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.CompareTag("ball"))
    {
        if (isplayer1goal)
        {
            Debug.Log("player1scored...");
            GameObject.Find("gamemanager").GetComponent<gamemanager>().player1scored();

        }
        else
        {
            Debug.Log("player2scored...");
            GameObject.Find("gamemanager").GetComponent<gamemanager>().player2scored();
        }
    }
}

}

rigid island
#

can you show the full inspector of the ball cause its cut off

#

why the hell are you spamming this shit

#

can you use the link like it was told to you multiple times

clear siren
rigid island
clear siren
rigid island
#

ok its confirmed

#

the error is telling you exactly what is wrong

clear siren
#

what does it mean notlikethis

rigid island
#
  1. the ball tag is missing
#
  1. it is not assigned to the ball
#

do you know what tags are ?

clear siren
#

. I SWEAR I SET THE TAGatwhatcost

rigid island
#

you never even created it in the first place according to the error

clear siren
#

must be bug i tagged it now

#

still showing same thin

#

thing

#

how do i assign it???

#

or define wtv

dusky lake
clear siren
#

yep did that set it to ball

dusky lake
#

in the screenshot it is still untagged

clear siren
#

somethings wrong with unity 😭

#

whenever i play the tag goes

dusky lake
#

have you set it on the prefab or the object in the scene?

spring creek
dusky lake
#

also stop play mode, then set tag, then start playmode

clear siren
#

oh.

spring creek
#

Ah yes. Changes in playmode are not kept

clear siren
dusky lake
#

that looks better, does it completely work now?

rigid island
tawny elkBOT
#

:teacher: Unity Learn β†—

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

rigid island
#

instead of some crappy 7 minute copy a whole game video

#

sure it works but its not teaching you anything , just copy n paste

clear siren
dusky lake
dusky lake
clear siren
#

how do i fix that

dusky lake
#

well... call the resetposition inside the player1scored and player2scored functions

wary coyote
#

just got back, will do

clear siren
#

so like in code?

clear siren
maiden heath
#

but that channel seems too active anyways

#

so nevermind

clear siren
#

ik thats why im doing it here sorry

maiden heath
rigid island
clear siren
#

i just need a solution man i been stuck forever

gray mural
maiden heath
#

and also i got an error when i made the class abstract so im trying to find out why

#

abstract allows function bodies right?

gray mural
#

That's what the error should tell you

maiden heath
#

or do i have them mixed up

spring creek
maiden heath
spring creek
#

It doesn't allow directly using the abstract class, but it DOES allow default implementation.

#

Sashok maybe confused it with the current .net level of interfaces?

dusky lake
maiden heath
weak spruce
#

Do I need to put a sphere collider on sheep or dog(player)?

gray mural
#

Well, when you create an abstract method within the abstract class, you cannot have a body for it. You must create a body when implementing the method in derived classes

public abstract class Foo
{
    protected abstract void MyMethod();
}

public class Bar : Foo
{
    protected abstract void MyMethod()
    {
        // the logic goes here
    }
}
dusky lake
spring creek
#

You know, I think yeah I am just wrong. I could have sworn you could
Apologies

spring creek
#

Ah, you can make a non-abstract method inside an abstract class which allows a body.

#

That's what I was misremembering

abstract class Animal 
{
  public abstract void animalSound();
  public void sleep() 
  {
    Console.WriteLine("Zzz");
  }
}
gray mural
maiden heath
#

thank you for clearing that up

rigid island
#

abstract class is very similiar to interface

#

except it deals with inheritance instead

weak venture
#

If I set script execution order of base class, do children inherit that if they dont specify any priority override for script execution order?

rigid island
#

iirc they don't

#

if you're messing with execution order though you might have a design problem

somber nacelle
#

I believe they do if you use the DefaultExecutionOrder attribute though

weak spruce
rancid frost
#

When using JsonUtility, how can i override the instance ID value with another one?
I have a scriptable object which holds a persistant ID, to the texture in question, how can I change it?
Thus far the best solution I have come up with is to manually subtring/replace the string, any other ideas?

leaden ice
#

and/or use a different serialization framework

rancid frost
#

Open to suggestions, Newston wasnt working

leaden ice
#

Newtonsoft works fine

#

it has its own rules you need to follow of course. It's very flexible/configurable

rancid frost
#

i tried messing with it, couldnt get it too work

modest brook
#

hey my button clicks aren't working, does anybody have any idea why?

`public void warrior()
{
Buttons.SetActive(false);
Warrior.SetActive(true);
}

public void mage()
{
Buttons.SetActive(false);
Mage.SetActive(true);
}

public void archer()
{
Buttons.SetActive(false);
Archer.SetActive(true);
}

public void druid()
{
Buttons.SetActive(false);
Druid.SetActive(true);
}`

tawny elkBOT
rigid island
#

also start with checking if you have Event System

#

if thats there, debug it by inspecting it during Playmode and uncollapsing its window at bottom of inspector

#

if you have the new input system it will only register on clicks unfortunately

modest brook
#

yeah and its saying the button is being pressed

rigid island
modest brook
#

alright

rigid island
#

Debug.Log($"Hello from {name}" , this);

modest brook
#

i'll try that now

#

thats working

#

let me try something hold on

#

nvm i know what the problem is thanks guys

dawn dock
#

Hey, I'm trying to set up a dialogue system that takes individual lines from a text document and displays only one line at a time in a dialogue box, I have the following code: https://hatebin.com/rmhzylkajs but i have no idea how to add only individual lines from the text file to the queue, ive been researching this for hours but can't find a solution, any ideas?

leaden ice
dawn dock
#

I see, so I can use a special code at the start or end of a new line to mark a new line?

rigid island
#

use TextAsset type

leaden ice
#

Also since you're not doing any kind of streaming stuff you can just use File.ReadAllText no need for streamreader etc

#

Oh yah that too

dawn dock
#

thanks

#

How would I go about making unity recognise a new line by a special character in the text document?

leaden ice
dawn dock
#

no?

leaden ice
#

Just use the existing newline character

#

New lines are marked by a special character already that's how the computer knows there's a new line

dawn dock
#

does unity automatically recognise \n?

leaden ice
#

It's just data

dawn dock
#

Oh, I see, so theres no need to force unity to recognise a new line, as it already will

leaden ice
#

Unity has nothing to do with it

#

Also

#

This exists

dawn dock
#

That seems useful, I'll check it out

#

thanks a bunch

maiden heath
#

i dont understand this error

#

im trying to call a coroutine

rigid island
maiden heath
#

so the values are null

#

theyre part of an abstract scriptable object class

maiden heath
hard estuary
rigid island
maiden heath
rigid island
#

because they're properties

maiden heath
#

i have to use [Serializable]?

rigid island
#

you can use
[field:SerializeField] with autoproperty iirc

rigid island
#

I normally just serializeField the private field

#

not common i touch properties with inspector at all though

hard estuary
# maiden heath i have to use `[Serializable]`?

[Serializable] is used before class/struct definitions to let your compiler know it should be serializable and lets you use [SerializeField] for fields of that class/struct. It's not an issue in your case, but this knowledge might be handy in the future.

maiden heath
#
void Update()
{
  switch (state)
  {
    case States.Initialization:
        Debug.Log("Battle state: Initialization");
        break;
    case States.PlayerWait:
        Debug.Log("Battle state: PlayerWait");
        break;
    case States.PlayerAttack:
        Debug.Log("Battle state: PlayerAttack");
        break;
    case States.PlayerItem:
        Debug.Log("Battle state: PlayerItem");
        break;
    case States.PlayerTalk:
        Debug.Log("Battle state: PlayerTalk");
        break;
    case States.EnemyAttack:
        Debug.Log("Battle state: EnemyAttack");
        break;
    case States.BattleWin:
        Debug.Log("Battle state: BattleWin");
        break;
    case States.BattleLose:
        Debug.Log("Battle state: BattleLose");
        break;
    case States.BattleDraw:
        Debug.Log("Battle state: BattleDraw");
        break;
    default:
        Debug.LogError("Battle state: NULL");
        break;
  }
}

how can i make this debug only ONCE then debug again ONLY if the state was changed again

maiden heath
#

what does [Serializable] even do tho

#

how do classes and structs get.. serialized?

hard estuary
rigid island
#

a scene essentially is just a serialized(making things neat) yaml file

#

like most assets

ebon leaf
#

does anyone understand abit about prefabs?

ebon leaf
ebon leaf
upper pilot
rigid island
ebon leaf
#

thx alot man

ebon leaf
upper pilot
#

np

#

Someone save me from Coroutines 😒
I am probably using them wrong, but at the same time it does exactly what I want it to do.

Pseudo code for a turn based auto combat(player does no interact during combat)

void StartCombat()
{
  isBattleStarted = true;
  isTurnReady = true;
}

void Update()
{
   if (isBattleStarted && isTurnReady)
   {
       StartCoroutine(DoBattle());
   }
}
private IEnumerator DoBattle()
{
  isTurnReady = false; // prevents Update from calling another coroutine
  yield return StartCoroutine(DoTurn());
  CheckIfBattleIsOver(); //this sets isBattleStarted = false to stop Update from calling another coroutine
}

private IEnumerator DoTurn()
{
  // some logic, might have yield break; to exit early
  yield return StartCoroutine(attackerSlot.DoAttack(defenderSlot));
  isTurnReady = true; //Enable update method from starting next turn
}
#

This makes both sides of 1 to 5 characters attack each other with the logic I wrote and it seems to work fine.
But I feel like I have to have IEnumerators everywhere in order to execute code in specific order.

#

I cant see how I could remove DoBattle IEnumerator, as I need to wait for turn to end before I can execute CheckIfBattleIsOver since logic is delayed inside coroutine.

#

attackerSlot.DoAttack is also an IEnumerator which has the delay for animation to finish etc.

upper pilot
#

Just to add to the above as I am working on it:

  public IEnumerator DoAttack(CombatSlot target)
  {
      MoveTowardsTarget(target);
      yield return new WaitForSeconds(0.5f);

      target.OnAttacked();

      yield return new WaitForSeconds(0.2f);

      target.ResetColor();
      MoveTowardsStartPosition();

      yield return new WaitForSeconds(0.5f);
  }
#

The flow is:
Update -> DoBattle -> DoTurn -> DoAttack

All 3 of these are coroutines calling next one and waiting for it to be finished before the previous one can continue.

lean sail
upper pilot
#

I just started using Coroutines, but yesterday someone said that I might be using them wrong(based on how I explained it at that time)

My question is: Is the above code a good use of Coroutines for what I am trying to achieve(turn based auto combat with no player input(yet))

#

Or should I avoid nesting coroutines like that.

lean sail
#

and as you're somewhat experiencing here, everything will need to be a coroutine or you'll have to use like WaitUntil

upper pilot
#

oh WaitUntil seems interesting I could actually use it if I do it right.
I can waitUntil next turn is ready for example.

hallow matrix
#

Would it be faster to have a list of strings and do a bunch of string comparisons (~20 comparisons) or have a Dictionary<string, int>, find the int via a string and then do int comparisons?

upper pilot
#

What are you comparing? Length of a string?

hallow matrix
#

anywhere from 5 characters to 100 characters in length

lean sail
rigid island
rain minnow
lean sail
#

πŸ€·β€β™‚οΈ it does matter what the actual comparison they're doing is. Like if this is just comparing the length of the string then theres no point in storing the lengths in a dictionary

hallow matrix
#

It is comparing the strings themselves to find if there are matching strings between 2 different lists. so anywhere from 10-100 strings per list. Each string can be anywhere from 5-100 characters in length. Each string will be unique so it could be assigned a number in a dictionary...

dusk apex
#

Why use strings?

hallow matrix
#

The user defines the strings/text.

spring creek
hallow matrix
spring creek
#

Your response did not seem to answer that (or the other question honetly)

hallow matrix
#

Yes user input is text. The int would be for an int to int comparison. It would be a unique number specific to that string.

spring creek
#

So an ID?

hallow matrix
#

yes

spring creek
#

You are assigning IDs to random user input, and checking if they have input the same thing before?

lean sail
#

Whats the int gonna do? if this is just a list of numbers, you'll still need to go through it anyways to find a matching one. you should really just use the profiler here and see that this will likely be instant anyways unless this is done like 1000 times per frame

#

if you can sort the strings, or use some other collection that'll make the comparison faster

hallow matrix
#

Yeah you're probably right that it doesnt matter. I am just over complicating it.

empty elm
#

Does anyone have an example of a centralized input manager for their player? The main advantage would be managing states and activating/deactivating the player from one place.
I understand how to use events to represent actions such as mouse click but movement scripts, for example, care about the inputs every frame. I don't think it's correct to use events if they're meant to be invoked every frame so how would you notify the observers?

vale bridge
#

Is there a "correct" way of making a rigidbody object face a certain direction constantly?
As in Quaternion.Lookrotation equivalent for rigidbody
Because I was told to not mess with transform once you have a rigidbody

lean sail
vale bridge
#

okie

#

I'll look into those

soft shard
mild goblet
#

any idea why this gpu instancing implementation aint working?


matrices = new Matrix4x4[size];
       



renderParams.material.enableInstancing = true;
material.enableInstancing = true;






for (int i = 0; i < size; ++i)
    matrices[i] = Matrix4x4.Translate(new Vector3(-4.5f + i, 0.0f, 5.0f));
       

Graphics.RenderMeshInstanced(renderParams, mesh, 0, matrices);```
keen lodge
#

I am developing a mobile app in Unity and need a script to save the app’s state when it closes, then restore it to that state when it reopens. Thire is oonly one scene.

How can I achive this?

waxen socket
keen lodge
waxen socket
hazy raven
#

hey guys, have an issue with iappurchases, i filled iapcatalog but when i check catalog items they dont have payouts which ive set, anyone faced that?

keen lodge
#

And then I have some other objects but they stay the same so dont know if I have to save them?

waxen socket
waxen socket
keen lodge
#

When a user presses a button one of theses spawns in a scrollveiw inside of the canvas and then I want them to be thire again when the user opens that app again.

#

Dosent Unity have a save scene or something like that that just saves everthing in the scene?

waxen socket
waxen socket
keen lodge
#

Thank you. This is what it looks like when it is opened the first time. Then when the user press the Add button a gameobjet (MainTaskAndSubTasks(Clone)) Spawns and inside of that one thire is a button called Done that then spawns (MainTaskHolder(Clone)) Inside of the MainTasksScrollview content.

Dont know if that makes senes.

@waxen socket

night elk
#

Hello, I have an error using ServerAuthenticationService.Instance.SignInWithServiceAccountAsync() I have a bad request error and I tried to resolve it for 2 days but I am really stuck, can anyone help me ?

somber nacelle
night elk
#

@somber nacelle Here is the error

#

And my code: ``` await UnityServices.InitializeAsync();

    try{
        await     ServerAuthenticationService.Instance.SignInWithServiceAccountAsync(
            " id", 
            "secret key");
    }catch(ServerAuthenticationException ex){
        Debug.Log(ex.GetBaseException());
        Debug.Log(ex.Message);
        Debug.Log(ex.Data);
        Debug.Log(ex.Source);
        Debug.Log(ex.ErrorCode);
    } ```
knotty sun
#

why are you passing the literals Id and secret_key rather than values from variables?

night elk
#

@knotty sun I changed them to send them to you, in my code they are correctly copied

lofty ether
#

How do I retrieve the old version in my unity project?

#

Like how do I access a project version that I worked on 15 mins ago?

somber nacelle
#

do you have some sort of version control set up?

lofty ether
#

Nope.

somber nacelle
#

well then i think you have your answer

lofty ether
somber nacelle
#

!vc

tawny elkBOT
#
Using version control in Unity

Unity Version Control

git Git

Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.

lofty ether
#

@somber nacelle can you use it in unity version 2021.3?

night elk
#

@somber nacelle so do you know how to help me ?

somber nacelle
#

ah wait, that's about that error i told you was regarding the UGS service (or whatever that sign in service you are using is) and not the actual code

night elk
#

I am using the Service Account from unity

somber nacelle
#

okay so then you need to check its documentation and maybe ask for help in #archived-unity-gaming-services (if the documentation is not sufficient) because it is not an issue with your code, but rather an issue with the request

night elk
#

Ok thx

merry stream
#

what's the go to way of triggering visual effects (hit splash, sword slash, particles, etc)? especially when there will be a lot of them. I've tried using vfx graph but sending events is super finniky or maybe I just don't understand it?

leaden ice
#

If you're using a ParticleSystem you'd use Emit()

merry stream
#

or I assume I'm doing it wrong

leaden ice
#

You're doing it wrong, presumably

somber nacelle
#

!collab πŸ‘‡

tawny elkBOT
golden wave
#

how easy or hard is it to protect variables from being changed with cheat engine by non-hackers that just read a simple cheat engine tutorial?

knotty sun
golden wave
#

I'm not asking for 100% security, I'm asking how to hide a variable from complete noobs who watched one cheat engine tutorial

knotty sun
#

How long is a piece of string? What tutorial, what cheat engine?

wise kindle
knotty sun
#

Even that is pointless, it is so easy to monitior the memory of a game and when the score, for example, changes to see which memory address is affected

wise kindle
#

I mean, yeah, but that would take actual effort

golden wave
wise kindle
#

I want to ask a question. If it's not an online game, why does it matter if people cheat?

knotty sun
golden wave
#

I was thinking to just add a random number to it for example
my health is 500
I generate a random number between 1000 & 100000 that I add to the health and then add that to health and save it?

somber nacelle
golden wave
#

But I don't know if CE detects that

wise kindle
#

That seems needlessly complicated

somber nacelle
#

it's going to be nearly impossible for you to prevent cheating with cheat engine if everything is done on the client

knotty sun
golden wave
#

πŸ“Œ Obscured Types β–Ά tutorial
Keeps your sensitive variables away from all memory scanners and searchers.
All basic and few Unity-specific types are covered.
Detects cheating attempts.

wise kindle
#

I mean, yeah, based on what I've just seen it could work

maiden heath
#

any idea on how to make a cutscene with dialogue like in undertale? i already have a dialogue system but now i want the player to be frozen and i want to control the person whos talking but i cant find an efficent way to do it without sphagetti code

golden wave
# knotty sun A complete and utter load of bollocks

mate you're not trying to help me, you're trying to prove your point, which is mute because I know and agree
I don't want to prevent cheating
I want to prevent people with absolutely 0 knowledge who watched 1 or 2 CE tutorials from cheating

knotty sun
onyx osprey
#

I got this snapshot from the profiler because i'm trying to find out why there's a framedrop to 15fps. The jobs are mainly staying idle and the main thread is not showing anything else then EditorLoop so i'm not quite sure what it's stuck or waiting on. I"m new to using this profiler so if anyone could point me in the right direction to find the cause it would be greatly appreciated

knotty sun
#

@golden wave You are throwing statements around like 'who watched 1 or 2 CE tutorials from cheating' which have absolutely no quantifiable answer

golden wave
golden wave
rigid island
golden wave
#

yes

rigid island
# golden wave yes

what you shown probably just works on singleplayer, multiplayer you wouldn't store anything on client

golden wave
#

all games store tons of things on the client, that's why so many games have cheaters
the player health is a good example again, I don't want my server to need to check the health after every attack - it would probably be better if I did, but that's not an option

chilly surge
#

You are going to get the same answer, client side anti cheat is futile, put your sensitive stuffs (data, logic, etc) on the server.

rigid island
golden wave
#

why do you all insist to not answer my question but instead give advice that I am fully aware of already?

rigid island
#

"tons of things on the client" is false

#

take a look at games like Path of Exile/ Diablo. They do not store playerdata on the client thats why you are connected to their servers

golden wave
#

but I'm not capable of writing a server like that and I do not wish to learn it at this time, so that is not an option

#

so it doesn't matter

rigid island
#

we call this "wanting the cake and eat it too"

#

so you want some magical solution to prevent client side cheating by without using any server verifcation methods.. Got it

#

well goodluck with that lol unrealistic expectation

golden wave
#

no, I'm just asking a very simple question here, that would probably prevent 90%+ of hacking attempts in my game
but instead I'm being told to go spend the next 3 months to learn how to build and adminster servers

golden wave
rigid island
#

the exploit video you shown shows a single player cheat πŸ€·β€β™‚οΈ

golden wave
#

yes, I know, that is what I'm asking

rigid island
#

if its singleplayer who cares about cheating, if its online deal with using servers to your advantage πŸ€·β€β™‚οΈ

chilly surge
#

I've also explained to you why "preventing 90% of wannabe hackers from cheating in your game" is not enough, when you said your game has an in game economy. It matters that just one single cheater can ruin your game economy so preventing 90% or 0% doesn't matter, your economy is going to get ruined either way.

rigid island
#

yike so you want ingame economy but don't wanna as you say "build and admin " servers, makes sense.

late lion
rigid island
#

no one saying there is something wrong with trying to do that though

golden wave
#

but I asked how to do it and didn't get single helpful reply
I even suggested a method I could think of

chilly surge
#

I am πŸ˜„

rigid island
#

all was said was getting your priority in order

rigid island
#

it all comes down to how you are going to manage the data..

golden wave
#

my priority is getting my game released, there is no time or budget for a server
so I'd rather have a game with lots of cheaters and a shit economy than no game at all

rigid island
#

why not have something good by putting the minimum required time to do so ?

golden wave
#

well I gave an example, my player health will be stored on the client
how do I hide it from the most basic CE searches?

rigid island
chilly surge
golden wave
#

why do I have to explain my entire project and life story to get an answer to a simple question lol

golden wave
rigid island
#

cause its not a "simple question" lol

late lion
rigid island
#

you're asking wat took very experienced engineers years to perfect...and even then still not good enough

#

its not a "simple question"

golden wave
late lion
golden wave
chilly surge
# golden wave thank you, why not?

CE can search not just absolute values, but also relative values. So your solution will prevent people from "seeing 500 health, search 500 health" but it will not stop people from "my health decreased, search all decreased values in memory, my health increased, narrow the search results to ones that just increased, repeat until I find the health."

#

That approach is extremely basic too, anyone that uses CE beyond a toy example will know it.

golden wave
#

so is there a simple method that would work? like encrypting the value? probably won't work too?

chilly surge
#

Nope

#

If there was a simple solution, Valve and all these giant gaming companies with practically infinite money would've solved cheating years ago, don't you think?

golden wave
#

I'd actually like to install CE and test it out on my game a bit, but I'm afraid I'll get banned from other games I have on my PC lol

late lion
golden wave
chilly surge
#

Sure, let me rephrase it: any anti cheat solution gives you exactly the amount of protection you paid for it. A free protection offers you zero protection because someone already cracked it because so many people use it for free, a $20 solution is probably already cracked (if not, will be cracked in the near future) because a lot of games can afford a $20 solution.

golden wave
#

yes I know, that is not what I'm asking

late lion
golden wave
#

Here's another suggestion:
Every time my Health variable is updated I generate a random number between -10000 and 10000 and add that to my health, so it could go up or down.

late lion
#

Security by obfuscation is very effective for small games, and basically useless for popular games. You need someone that knows what they're doing to sit down and figure out how to bypass your protections. The smaller the game, the less likely there will be someone who does that, and vice versa.

chilly surge
#

People can still find your health value by "scan the memory, move around but don't change your health, narrow the result to values that haven't changed" or "scan the memory, change your health, narrow the result to values that have changed" combine the two and repeat multiple times to find out where your health variable lives in the memory.

golden wave
#

that already sounds a lot harder than what was shown in the 1st minute of that video

chilly surge
golden wave
#

probably still not enough though

golden wave
chilly surge
#

I feel like if you keep coming up with potential solutions, this chat will turn into me teaching people how to cheat in games 🀣

golden wave
#

I guess I'll just go buy the anti cheat asset πŸ™‚

ebon leaf
#

my fireball does not go to the left instead it goes to the left and falls as if there was gravity but the fireball has no rigidbody or anything that gives it gravity

maiden heath
#

since override completely overrides the function, is there a way to just add functionality to it instead of overriding everything?

chilly surge
#

Call the base method in your overridden method.

ashen shuttle
maiden heath
last island
#

How do I ensure that all scenes are loaded in Unity? Currently when I start a play session 2 scenes are loaded; A preload scene that lives in the game always with a couple of elements for all other scenes and then the actual scene I play in.

However I have 2 other playable scenes that are not registered anywhere other than in the buildSettingsCount. That's it. So if the build indices are 0, 1, 2, 3 I can only access 0 and 1. How do I get Unity to load 2 and 3? According to the SceneManager those scenes don't exist.

last island
knotty sun
#

well done, obscured the name when I was going to tell you to load by name

last island
#

I mean, I can still use the names just because you can't see them

somber nacelle
last island
#

sceneName turns out null

somber nacelle
#

sceneCountInBuildSettings 4

last island
#

Yes

#

I am well aware

#

I even said as much

somber nacelle
#

so it sees that the scenes exist

last island
#

But when I use the count and GetAt methods it says that the index is invalid

somber nacelle
#

did you actually look at what those are?

last island
#

Yep. I can check again.

somber nacelle
#

You should read the documentation for them

knotty sun
#

and this does not work?

last island
#

newSceneIndex 2 is correct

#

activeSceneIndex 1 is correct

#

sceneName comes back null because 2 is invalid index

somber nacelle
#

and again, have you read the documentation for that method?

last island
#

What method

#

Be specific

somber nacelle
#

GetSceneByBuildIndex, you know, the one that is returning null

last island
#

Yeah it says I can't return a valid scene if the scene isn't added to the buildingsettings and is already loaded.

#

I specifically asked up top

#

How do I ensure they are loaded

somber nacelle
#

before we go any further, is there even a reason you need to get the scene name? you can load by index. but also you have to actually have the scene loaded for that method to work

last island
#

I feel like we are having two separate conversations.

#

How do I load

#

How do I ensure the scene is loaded

somber nacelle
#

for what purpose

last island
#

I need to switch scenes.

somber nacelle
#

and have you just been completely ignoring the part where we've been telling you to load by the index? you don't need to use that GetSceneAtBuildIndex method at all

#

you do not need to get the scene name to load it. if you already have the index

pearl burrow
#

hi guys! Need a tip.

Some of the item i can pick up in the game go into the inventory and stay there for a fixed amount of time giving you every second X amount of resources, then it disappear. Since you can get more of these item in the inventory i have a variable that checks how many "ticks" i get each seconds. So lets say one item gives you 1 resource per second, the tick is 1. Then if you get another the tick is 2. When one item expire the tick is subtracted so when there are 0 item the resource is 0. I did this in the update function checking if tick > 0 and checking every seconds.

My question is, since im checking in the update an if condition that might be not fired at all (if the user never get the item for whatever reason) is there a better way to do it?

last island
somber nacelle
#

to ensure a scene is loaded you have to actually . . . load the scene. it's literally that simple

#

your issue was that you were attempting to use a method to get an unloaded scene just so you could load that scene. if you have the scene's index, just use that

last island
#

"Using the index would be enough to ensure the scene is loaded" could have been the answer.
I felt I wasn't being heard. But at least a solution was found πŸ‘

rigid island
#

though update should still be fine

somber nacelle
last island
#

If you propose to help, then it's on you to also address what is being said rather than trying to brush it aside as if what is said is a given. I felt the answer "how do I ensure things are loaded" was never answered, and it wasn't. Instead it was about being coy.
"have you read the documentation?"
"Yeah what does it say?"
That's not helpful. That's sneering. So of course things get adversarial.

last island
somber nacelle
# last island If you propose to help, then it's on you to also address what is being said rath...

if we had just answered your question about how to ensure your scenes were loaded, the answer would have been to use SceneManager.LoadScene(Async) for each scene. So do you think it would have been appropriate to answer your question with that, or do you think getting more information then providing the info about using the index like we had done was the more appropriate course of action to solving your issue?

last island
#

And now I have the issue I've had to solve before that I forgot how I solved.
You load Scene A and B additively.
You unload scene B while loading C additively.
B does not get unloaded as you'd expect. But if you then then load B again and unload C it seems that C does not get unloaded πŸ€”

I realise Unity does some stuff to save on resources there but I'm sure this is a well-known problem solved by many before.

last island
somber nacelle
#

and yet this whole thing would have been avoided had you read the documentation

last island
#

No. Because I already had and I even quoted it back at you to underline that I had read it and that my question had not been answered; how to ensure scenes were loaded.

#

Should probably move on though.

placid summit
#

this is very C#, but if you want to remove all subscribed Actions/delegates from a class when it is gone (or Destroyed for Monobehaviour) is there a cleaner method then unsubscribing every one at this point (in OnDestroy on Monobehaviour). Perhaps there is a pattern to manage event subscriptions?

rigid island
#

multiple, custom too
EventAggregator pattern maybe?

knotty sun
chilly surge
#

Make a MyMonoBehavior class or whatever you want to call it, let it keep track of a list of subscribed events. Have a SubscribeTo method, which subscribes to an event and puts it in the list to keep track of. On destroy, loop through the list and unsubscribe.
Now to use it, instead of inheriting from MB like you usually do, you would inherit from MyMB instead, and you subscribe to events using the SubscribeTo method, and that's it, on destroy it will automatically unsubscribe everything.

#

There are some limitations with this solution unlike a reactivity system, but for simple use cases you don't need to worry about "oops forgot to unsubscribe now I have a hidden leak that might lead to hard to detect bugs."

rigid island
chilly surge
#

Probably a List<Action> so it's more flexible, but yeah.

#

This solution kind of sucks that you must subscribe using the method or else it won't be tracked which limits your flexibility, unlike a reactivity system.

fringe light
#

Anyone have some suggestions for the best way to tell if a player is moving an object in one of the cardinal directions? Like are they moving up, down, left, or right?

waxen socket
fringe light
last island
knotty sun
slate imp
#

Hi there, I've got an issue with terrains, i don't know why i have a couple of terrains that does not appear when building the game, in playmode everything is okay but whenever i build the terrain, the floor is transparent...

spark flower
#

hey guys, how do i get 0-360 degrees from transform.rotation.eulerAngles.z ?

#

i know about rad2deg but that is just a value and i think it pushes the value just to 180/-180

cold parrot
spark flower
#

so if the degrees is negative i do rad2deg * eulerangles.z + 360 and if its positive, i just do rad2deg * eulerangles.z ?

#

@cold parrot

cold parrot
leaden ice
#

There are probably better ways to approach it than reading euler angles from a Transform, which has a lot of pitfalls

placid summit
placid summit
#

Delegates just seem bad design as hold references to classes

placid summit
echo jungle
#

!code

tawny elkBOT
echo jungle
#

For some reason start and update dont work in my code but fixedupdate does

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collidable : MonoBehaviour
{
    public ContactFilter2D filter;
    private BoxCollider2D boxCollider;
    private Collider2D[] hits = new Collider2D[10];
    private void Start()
    {
        Debug.Log("F");
        print("A");
        boxCollider = GetComponent<BoxCollider2D>();
    }
    private void FixedUpdate()
    {
        //print("GDS");
    }
    private void Update()
    {
        boxCollider.OverlapCollider(filter, hits);
        for (int i = 0; i < hits.Length; i++)
        {
            if (hits[i] == null || hits[i] == boxCollider)
            {
                continue;
            }
            print("G");
            OnCollide(hits[i]);
            hits[i] = null;
        }

    }
    protected virtual void OnCollide(Collider2D coll)
    {
        Debug.Log(coll.name);
    }
}
leaden ice
echo jungle
leaden ice
#

Also the FixedUpdate print is commented out

#

so showing the code as it actually is when you run the game is essential as well

#

(btw there is no print in Update right now, except for the one inside a conditional statement)

flint panther
#

I am working on spawning the enemies. I have a function to do it, but I want to make a check for if the position is a bad one (has colliders blocking)

#
    public static Enemy SpawnEnemy(Vector3 position) {
        CapsuleCollider check = I.enemyCheck;
        if (Physics.CheckCapsule(position, position + Vector3.one * check.height, check.radius)) {
            print("Tried to spawn enemy in an invalid position.");
        }
        return Instantiate(I.enemy, position, Quaternion.identity);
    }```
#

I have done this, but now I want to find the closest "valid" position. Is there algorithm to do this easily?

gusty aurora
#

Is there any situation where is it useful to set HideFlags.NotEditable on top of HideFlags.HideInInspector ?

gusty aurora
cold parrot
#

Count the punches, if 0 then left, if 1 then right. To alternate forever: if count % 2 == 0 then left, if count % 2 == 1 then right

#

You should also call the invoked methods directly through a reference to the script component that has them.

hard estuary
# flint panther I have done this, but now I want to find the closest "valid" position. Is there ...

I think it depends on the scenario. Mentioned Physics.ComputePenetration could work assuming you only need to push spawned enemy away from the initial collision. The thing is, the collision can occur again, with another object. You can repeat the process in the loop, but I think there would be a risk for this loop to be endless (unless you also push other colliders, effectively spreading them out).

I think the simplest way of dealing with the problem would be simply to set spawn points and spawn enemies inside of an unoccupied spawn point. It should work as long as at least one spawn point is not occupied. You can also add some triggers to those spawn points to automatically set them as occupied/unoccupied. The spawn points could be either placed manually or baked with some algorithm. The things would be simpler for grid-based games, since those already divided the game into small zones. If you want to keep analogue precision, I suppose you could create some variation of a quadtree, but I believe simple solutions are a better choice.

flint panther
hard estuary
flint panther
#

I am using navmeshes, I will look into this

stable osprey
#

My preferences window looks like this though:

merry stream
#

project settings

stable osprey
#

I've already changed those -- but these are specifically for play mode

#

I want Unity to not reload each time I hit ctrl+s in Visual Studio for every small change

swift falcon
#

its painful especially when your just adding comments

stable osprey
#

I used to have a hack for it which involved changing EditorUserSettings.asset or EditorSettings.asset directly but I don't remember what it was lol

swift falcon
#

i just accepted it xd

dusky lake
#

Hey I am planning a little experiement with Unity ECS, is there a way to get all entities that had a certain componennt changed? Like a reactive way to query entities

tardy beacon
#

im thanking god enums exist rn

#

enums are making this thing im trynna do a little easier and fun

spring creek
upper pilot
#
yield return new WaitUntil(() => CombatManager.Instance.animationSpeed > 0);

Is it possible to make this code multi line? What is the syntax? Adding { } doesn't work

chilly surge
#

You need to return ...; after adding {}.

upper pilot
#

ah thanks

#

That worked, is there a reason why I have to return?
I assume that the above is a shortcut that already returns behind the scene?

chilly surge
#

In a statement block, return is how you return.

upper pilot
#

oh it has to return boolean for the WaitUntil to know when to stop the loop

chilly surge
#

Expression body is just a short way to write a block that contains only return.

#

There's no implicit return in C#, we are not Rust here πŸ˜„

upper pilot
#

Makes sense similar to properties

#

I found a post from 2011, I wonder if this is still a thing or if it should be avoided at all cost?
Perhaps Coroutines werent a thing back then?

function Update(){
MakeThis();
}
 
function MakeThis(){
//make this first thing
yield WaitForSeconds(2)
//make the second thing..
}
chilly surge
#

I don't think that's valid C# code.

upper pilot
#

Perhaps its from JS times

leaden ice
#

that is definitely a JS (UnityScript) snippet

#

it is a coroutine though

chilly surge
#

Not valid JS either, MakeThis is not a generator function.

#

(Did Unity version of JS ever support genreator functions?)

leaden ice
#

It's UnityScript

#

This example is from there^:

function Fade() {
    for (var f = 1.0; f >= 0; f -= 0.1) {
        var c = renderer.material.color;
        c.a = f;
        renderer.material.color = c;
        yield WaitForSeconds(0.1);
    }
}```
#

UnityScript isn't exactly JS

#

but it's close

chilly surge
#

I feel like UnityScript and Boo were such dumpster fire. They look like the languages but not exactly, so you could use zero of the mature ecosystem. At least they got C# right that we are not locked out of .NET ecosystem.

leaden ice
#

C# is partially right. We're still not totally in the ecosystem. We can't use NuGet (easily), We can't manage assemblies in a normal way, etc.

chilly surge
#

(I also feel like they are repeating the same mistake by reinventing CSS/HTML but I guess it's better than nothing)

tardy beacon
gray bough
#

How can I draw an ellipse with code in the UnityEngine library?

rigid island
#

well that was fun..

gray bough
#

You don't have to use your hands to draw the code and then draw it right away
ellipse πŸ€”

gray bough
rigid island
gray bough
rigid island
#

that is very vague, everything you do is a function because they are part of doing anything lol

leaden ice
#

I'm pretty sure there's a language barrier/translator involved in this discourse

rigid island
#

seems that way lol

gray bough
#

that's true

swift falcon
#

Question:


    void VelocityControl()
    {
        Vector3 currentVelocity = new Vector3(rb.velocity.x, 0, rb.velocity.z); //Current player velocity

        if (currentVelocity.magnitude > current_setting.speed) //Check if velocity is over max speed
        {
            Vector3 fixedVelocity = currentVelocity.normalized * current_setting.speed; //Sets velocity to 1, then to the max speed allowed
            rb.velocity = new Vector3(fixedVelocity.x, rb.velocity.y, fixedVelocity.z); //Changes it in-game
        }
    }

So this ensures the player has the same speed when he is moving ||(Ofc some floating point differences but who cares)||
However when the player is in the air, the drag is 0, but when its on the ground its 5. So the speed is different in the air

So im wondering how I could make that code account for drag somehow? Right now I have to manually slow down the player by multiplying the speed by a small value when hes in the air. This seems quite complicated

#

I dont think its even possible

#

I guess it has to change fixedVelocity using the drag value somehow

leaden ice
swift falcon
#

if thats what you mean by separate variables

leaden ice
#

Well your code is just directly normalizing the input and setting the speed

#

So no

#

Just using a different speed variable when grounded vs in the air

scenic sigil
#

Hello. When I build my game, one specific sprite just disappears. Somewhere it becomes a white rectangle, somewhere it's fully transparent. What to do? How to make it show up? It's not a sorting layer issue.

#

Editor/Build

#

Googling gave me nothing

ebon leaf
rigid island
scenic sigil
#

This is build problems

rigid island
#

looks like a UI problem to me

#

unless you're loading the image via code ?

#

or like remotely

tawny elkBOT
scenic sigil
#

im using an Image with this sprite

#

the sprite vanishes in all uses

#

either white rectangle or nothing

rigid island
#

and where are you getting sprite from

scenic sigil
#

Assets/Sprites

ebon leaf
# rigid island !code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FireBall : MonoBehaviour
{
    public GameObject ball;
    public GameObject[] spawn;
    int minNum = 0;
    int maxNum = 2;
    public float ballSpeed;
    GameObject player;
    // Start is called before the first frame update
    void Start()
    {
        player = GameObject.Find("Player");
        
    }

    // Update is called once per frame
    void Update()
    {
        
        Invoke("FireballInstantiate", 5);

        ball.transform.position = Vector2.MoveTowards(ball.transform.position, Vector2.left, ballSpeed * Time.deltaTime);
    }
    void FireballInstantiate()
    {
        Instantiate(ball, spawn[Random.Range(minNum, maxNum)].transform); 
    }
}
swift falcon
rigid island
#

also might just want to make a timer with Time.time for example, that Invoke in Update especially not even using nameof

leaden yew
#

I implemented unity ads in my project and I don't understand why I can only see 8 ads (then something with "no fill" appears)

ebon leaf
#

the ball doesnt even get spawned btw

rigid island
ebon leaf
rigid island
rigid island
ebon leaf
rigid island
#

are you cloning a scene object with ball

#

instead of using prefab

ebon leaf
ebon leaf
rigid island
#

no i wanted to know if you were cloning ball as a scene object instead of using a prefab πŸ€”

wide terrace
rigid island
#

like I said, the new object isn't moving because you never assign it to the instance spawned

#

as to why its not spawning you are not assigning it a position so its prob spawning at world 0

ebon leaf
#

im assigning it to a spawn point

#

in a gameobject array

rigid island
ebon leaf
#

but it spawned somewhere else

#

so how can i assign it to a spawn position and not parent it

rigid island
#

you see you're only assinging a parent not giving it position

#

the Vector3 is for position

#

use the correct signature

#

also you see the return value is Object

rigid island
#

if you don't know what it is click it

ebon leaf
#

no, i do

#

its just that i was experimenting different methods since i was experiencing issues

rigid island
#

well sounds like a case of I didn't look at the manual first πŸ™‚

ebon leaf
#

i still dont know how to instantiate the object in the position that i want

#

and in the direction i want

rigid island
#

vector3 is a position

ebon leaf
#

alr let me try that real quick

rigid island
#

do you need the parent ? you dont have to parent it

ebon leaf
#

nah i dont need to parent it

#

hey quick question

#

whats the diff between time.deltatime and time.time

#

@rigid island

#

like if i wanted something to instantiate every 5 seconds

wide terrace
# ebon leaf like if i wanted something to instantiate every 5 seconds

Time.deltaTime is the number of seconds which have passed since the last frame. Time.time is the number of seconds the game's been running.

You can use either to manually manage a timer. Or InvokeRepeating() or coroutines, in which case you typically wouldn't need to use either for this use-case.

rigid island
ebon leaf
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FireballMovement : MonoBehaviour
{
    public float ballSpeed = 10;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = Vector2.MoveTowards(transform.position, Vector2.left, ballSpeed * Time.deltaTime);
    }
}
ebon leaf
#

instead it starts falling down slowly

#

i have no rigidbody attached to it so gravity shouldnt be affecting it or anything like that

cosmic rain
ebon leaf
#

oh yea it needs a target

#

i forgor xd

vivid halo
#

I'm trying to pair scriptable objects 1:1 with a corresponding method, and I'm not sure how to go about it.

I want to use a scriptable object to store spell/ability configuration data, but also have a method that performs the spell cast/ability cast.

What is the best way to map these together? {AbilityConfigData, AbilityMethod}

gray thunder
#
public interface IAbility
{
    void Execute(AbilityConfig config);
}
#

You could do something like this

#

And for example

#
public class FireballAbility : IAbility
{
    public void Execute(AbilityConfig config)
    {
        Debug.Log($"Casting {config.abilityName}");
    }
}
#

Then you create some kind of abilityManager

#
private Dictionary<AbilityConfig, IAbility> abilityMapping;

public void ExecuteAbility(AbilityConfig config)
    {
        if (abilityMapping.TryGetValue(config, out var ability))
        {
            ability.Execute(config);
        }
        else
        {
            Debug.Log($"No ability found for {config.abilityName}");
        }
    }
modest brook
#

does anybody know how i can make a cooldown in c#? i have tried a few things but they aren't working

unique flower
#

why the code doesn't work

knotty sun
#

A simple coroutine @modest brook

coolingDown = true
yield WaitForSecondsRealtime(coolDownTime)
coolingDown = false
unique flower
#

it doesnt work for me at least i have another way if it doesnt work with you @modest brook

modest brook
#

i have tried that

#

whats your way marwan?

unique flower
#

make a varible first
float poweruupcooldown = 10f;

update (){
poweruupcooldown -= Time.deltaTime;
//that will make the code subtract 1 number from powerup cooldown at when a second end
}

#

that is my code

somber nacelle
# modest brook i have tried that

show what you actually tried, because a cooldown is incredibly simple and what steve showed absolutely would work, so you probably did something wrong

unique flower
unique flower
#

by the way can anyone help me now ?

knotty sun
somber nacelle
modest brook
#

public GameObject Axe; public float CooldownDuration; public float timeStamp;

void Update() { AxeHit(); timeStamp = Time.time + CooldownDuration; }

` void AxeHit()
{
if (Input.GetMouseButtonDown(0) && timeStamp <= Time.time)
{
Axe.GetComponent<Animator>().Play("Hit");

 } 

}`

somber nacelle
#

three backticks, not just one. and you're just constantly increasing timeStamp so it is never possible for it to be less than or equal to Time.time (unless CooldownDuration is 0)

modest brook
#

i was thinking that tbf but its one that i got online that people said worked

somber nacelle
#

You must have misunderstood the code you saw "online" because that could never work. However if you change where you set the cooldown it could work. you need to set the cooldown when you actually perform the action that requires the cooldown, not every single frame

modest brook
#

so should i put timeStamp = Time.time + CooldownDuration; in AxeHit()

knotty sun
modest brook
unique flower
#

thx sooooooooooo much @somber nacelle

modest brook
knotty sun
modest brook
#

bit harsh but yeah

#

i've tried to do a timer before but its just not worked for some reason

#

the code i have rn is just saying when the mouse clicks play the animation of the axe hitting

knotty sun
#

look ar this

 void AxeHit()
 {
     if (Input.GetMouseButtonDown(0) && timeStamp <= Time.time)
     {
         Axe.GetComponent<Animator>().Play("Hit");
         
         timeStamp = Time.time + CooldownDuration;
     } 
 } 

now think, when will the if be true once it has been executed once

modest brook
#

well never because the timeStamp will always be above Time.time and the timeStamp has to be lower than time.time for the code to run

knotty sun
#

not true

modest brook
#

oh wait its inside the if statementr

#

i'll try that and see what happens

#

for god sakeπŸ˜‚

#

it was ONE SMALL THING

#

but, thanks

knotty sun
#

now do you think I was harsh?

modest brook
#

yeah BUT i was thinking this before anyway and its just a good way of teaching lol

#

also i've spoken to you before like almost a year ago cheers

#

@knotty sun im comparing you to Rick from rick and morty

knotty sun
#

no idea who they are

modest brook
#

fair he's just a good teacher

#

its a compliment

#

πŸ‘

scenic sigil
#

Howdy. In my game, on one device the sprites are normal, but on other devices, some sprites are much brighter. I tested on my machine and a VM (due to lack of other devices). Here is a comparison: host/VM

scenic sigil
placid summit
#

with SceneManager.LoadSceneAsync( name, LoadSceneMode.Single );) the current scene elements seem to stick around for a second or 2 even though it should be unloading it immediately. I have dontDestroy things to show a loading screen but do I need to hide all elements in a scene before loading the next to be sure they immediately hide? Especially UGUI

#

Or is the Async just not needed and I should use LoadScene

deft dagger
#

hey i have a question about something in blender but i cant find the right channel to ask in, is there a channel for that or do i need to find another server that is for blender ?

knotty sun
#

!blender

tawny elkBOT
deft dagger
weak spruce
#

whats wrong with the sheep?

#

i tried to fix it for 2 day

lean sail
weak spruce
lean sail
lean sail
# weak spruce i write it myself

You should add more useful things to your debugs, because just a string doesnt tell you anything. Methods like Debug.DrawRay can help u visualize where the sheep is trying to move from your code. Look at your code logically too, casting in 4 directions here doesnt make much sense, especially considering you potentially move it between casts while using the original point. You could just use one larger overlap sphere or some trigger collider and the unity physics messages. Theres a lot of other minor issues, but probably best to fix those after

weak spruce
ebon leaf
somber nacelle
#

are you trying to drag scene objects into a prefab?

ebon leaf
#

lowkey yea but it wont let me do that with a normal object either

somber nacelle
#

prefabs cannot reference scene objects because those scene objects simply do not exist until the scene is loaded but prefabs do exist at all times

#

assets (like prefabs) can only reference themselves and other assets

ebon leaf
somber nacelle
ebon leaf
#

to refrence a scene object in a prefab

maiden heath
#

enemyAnimator.runtimeAnimatorController = animator.runtimeAnimatorController; is this the correct way to set a components animator to another components animator? because it isnt working for me

somber nacelle
maiden heath
#

i assigned it in the inspector and everything

somber nacelle
#

then one of your two variables are null at the time that line runs

ebon leaf
#

just curious

somber nacelle
ebon leaf
#

ah ok

sterile gorge
#

Hey Folks, so we were trying to create a Pool class for gameobjects but to implement it specifically for gameobjects we would need it to inherit from monobehavior. Is there a way to do it without inheriting monobehavior?
Basically, I want to do something like this:

{
Gameobject[] pooledObjs;
void addToPool(Gameobj)
Gameobject getFromPool();
etc.
}```
#

I was thinking I could forward declare Gameobj but I saw in a few search results that C# doesn't allow it

somber nacelle
sterile gorge
#

can you explain a bit on the create an instance bit?

ebon leaf
somber nacelle
somber nacelle
ebon leaf
somber nacelle
#

then take a break and come back to it after you've slept. don't make your lack of sleep everyone else's problem

ebon leaf
#

alr take it easy

sterile gorge
#

wait no im familiar with new, so do you mean just like

{
GameObj[] Pool = new List<GameObj>();
}```
somber nacelle
#

no that's not at all what i was referring to. that's also super wrong

#

i was referring to creating an instance of your Pool class. you do need to initialize your array, but arrays are not lists

sterile gorge
#

ill take my questions elsewhere

somber nacelle
#

fun fact, but constructive criticism is not an attack on your person. don't take things so personally

sterile gorge
#

there's constructive criticism and then there's a tone of superiority complex, for obvious reasons, I don't want to get into online arguments, so thanks

somber nacelle
#

or maybe, i was literally just providing you information. but if you're so insecure that you took it as an attack or a "superiority complex" or whatever, maybe look inward to find out why that is

ebon leaf
#

I dont want to fuel anything especially because you were helpful to me before but i felt a similiar way as jako and its no biggie but abit of patience with us would be nice

cosmic rain
#

I'd say the issue is posting in a wrong channel. #πŸ’»β”ƒcode-beginner would be more appropriate for such questions. People would be more tolerant to you if their expectations match reality. In this channel we expect you to know what creating an instance means.

weak prairie
#

(sorry just realized there's a postprocessing channel)

ebon leaf
# cosmic rain I'd say the issue is posting in a wrong channel. <#497874004401586176> would be ...

imo its still no excuse to be impatient with developers and sometimes its difficult to tell whether your question is classified for the beginner channel or general channel, you can guide us if we misunderstood and not just once but each time we forget because after all this is what you are here for right? its to guide us and be patient with us. we are not here to engage in arguments and drama online but we are here to just get the help we need with our codes and game development, thanks.

somber nacelle
# ebon leaf imo its still no excuse to be impatient with developers and sometimes its diffic...

the channels are for your own skill level when asking for help, it is not dependent on the channel. also "this is what you are here for right"
people who help here do so in their free time. there is no obligation for people to help you, so you need to put in the effort to try to understand the help being provided to you. if you do not understand something then it is on you to actually ask clarifying questions instead of just simply insisting you want examples (especially when the resources provided to you have examples)

#

also i was impatient with you specifically because you were not paying attention to what i was telling you so i had to repeat the same information multiple times before you finally understood that assets cannot reference in-scene objects and the page i provided to you showed you how you could pass a reference to an in-scene object to a prefab instance that was spawned into the scene

ebon leaf
somber nacelle
#

alright i'm done entertaining this. have fun fumbling around without understanding any of what you are doing

gray mural
#

When changing a variable value in the Inspector and having the OnValidate method called for it, is it possible to avoid "Modified value in MyScript" being saved in Undo History?

#

Or, perhaps, a different approach: change the objects to undo

leaden ice
vale bridge
#

Is there a way to subscribe to Actions without having a reference to the script that owns the reference?

#

Are static Actions a thing?

somber nacelle
#

yes

vale bridge
#

I assume that the disadvantages are the same as static fcns where you obvsly can't access non static members

#

Actually that shouldn't be a problem

#

Now that I think of it

#

Since I only want to subscribe to some event that gets invoked via logic anyways

#

Actually, why shouldn't one make all Actions static?

gray mural
somber nacelle
#

nope, the main drawback of a static event is that you have to make sure you are unsubscribing from it when the object is no longer in use. non-static events would just get nulled out when the instance they belong to are destroyed/GC'd but static will of course persist

vagrant blade
#

I use static actions a lot to broadcast from things like managers, but as boxfriend said, make sure you're unsubscribing from them. Especially if you turn off domain reloading.

gray mural
vale bridge
#

So for example in that case you'd call onDead for this specific enemy and you'd want the specific sfx be applied to this specific location or whatever, which makes using static Actions not very great, is that right?

waxen socket
gray mural
placid summit
vagrant blade
#

In that specific case, you could have a static action that is called so that things can "generically" react to the death of an enemy, to play a sound effect I suppose.

But personally I'd just call it directly off the AudioManager.PlayDeathSound();

#

Otherwise, your AudioManager will have to subscribe to every enemy that gets spawned in.

vale bridge
vagrant blade
vale bridge
vagrant blade
#

Fortunately Copilot auto fills these out

gray mural
placid summit
#

I feel like it is a weakness in C#

somber nacelle
vale bridge
#

right

#

So as long as I subscribe and unsub all events we're good?

somber nacelle
#

yep

vagrant blade
#

Generally speaking, if you're typing out code to subscribe to something, immediately put in the code to unsub it somewhere so you don't forget.

vale bridge
#

I'm starting to think if I should design everything around Actions since they're so useful to separate features, how true is this?

placid summit
#

an event keeps a reference to all classes that subscribe to it so they will never actually be GC'd until you unhook your delegate

vagrant blade
#

Because they're extremely difficult to track down if you do

vale bridge
#

but I will defo do this from now on

leaden ice
somber nacelle
gray mural
vale bridge
late lion
#

And I would suggest using OnEnable/OnDisable for subscribing/unsubscribing. Some people use Awake/OnDestroy or Start/OnDestroy, but that means the listeners will react to events even when they are disabled, which is likely going to be confusing. OnDisable is also invoked when the script is destroyed.

placid summit
vale bridge
#

Roger that

leaden ice
vale bridge
#

Omw to write horrible code and fix them later

placid summit
#

github has many attempts to make Events that hold a weak reference to subscribers but it has not become part of C# outside WPF .Net

late lion
#

I view static events the same way as I view Singletons. Extremely useful, but also easy to abuse and run into spaghetti problems down the line.

vale bridge
#

Guess I'll have to find out

#

I'll be back when the spaghetti is cooked

#

Thanks for all your answers guys!

#

Very helpful

thin aurora
#

I believe there are hook like systems that are garbage collected and these also unsubscribe your events, but they pretty much will have the same issue as MonoBehaviours

placid summit
#

same differences, different on destroy

thin aurora
#

That one will also have the same issue; object might already no longer be used when an event is invoked

placid summit
thin aurora
#

When in doubt, VS has analyze options that when enabled can warn you of undisposed classes

thick terrace
#

IDisposable is usually the way to go, finalizers have all kinds of caveats

#

don't forget using statements/blocks for dealing with it, it makes it a lot easier!

placid summit
#

replied to wrong message!

uneven slate
#

Is there any way to set up buttons to activate on mouse down as opposed to mouse up? I'm fine with adding stuff to it if need be, but going through and changing every prefab and script that uses Button would be a PITA, so ideally it's just something I can tape on (or change at a settings level).

waxen socket
uneven slate
#

Yeah, that'd involve changing every script/prefab that uses buttons lol, hence I'm trying to avoid

waxen socket
uneven slate
#

yeahhhh that's also a PITA. I'll look into it.

slim gate
#

Hey, maybe someone can point me in the right direction:
I am trying to do probabilities for different resources to spawn in my game. My current approach is an animation curve, which works fine enough for me but I want a solution in code so that players can add their own through mods later on. The animation curve is from 0 to 1 and I just check the curve at current progress in the game. (On level 5/10 i check the curve on 0.5; etc)
I want to be able to control this somewhat, like: When is a resource most likely to spawn, when does it start and end spawning, etc.

#

This is an example of the types of curves I have right now

#

What would be a proper way to define these in code?

knotty sun
#

easy way is a Vector2 array

slim gate
#

How do you mean?

knotty sun
#

each point on your curve can be expressed as a Vector2

slim gate
#

That seems very troublesome to do though doesnt it?

#

If I wanted to add something new then I would have to manually declare a ton of vector2s

knotty sun
#

how else would you do a data representation modifyable via code?

slim gate
#

I have no idea, that why I am asking

#

Cause everything I can think of is more troublesome than animationcurves

knotty sun
slim gate
#

Another idea I had was to just define the highest spawnrate and when it is and then just calculate the "difference" from that and have some set falloff

knotty sun
#

you could even use Lerp between the points to define even less of them

#

So your red line here could be defined by 4 Vector2's

slim gate
#

ahh I get it

#

Yeah that might be a better way with more control

#

I will try it out

leaden ice
knotty sun
#

I'm guessing as he mentioned modding he wants to read it as data

uneven slate
#

Is there seriously no way to do something as simple as "This button should click on pointer down, instead of requiring down and up"?

vagrant blade
#

Also accessible on the EventTrigger component if you don't want to use code.

uneven slate
#

Eugh. Gotcha.

tawdry forge
#

Hello, my question isnt related directly to scripting but I think many of you use Rider as your IDE.
How did you manage to use an editorconfig with Rider in Unity projects ? I dont know why but my Rider doesnt use the file when formatting

rigid island
#

!ide

tawny elkBOT
tawdry forge
#

For some reason when I create the file in the asset folder Rider doesn't use it when formatting.
For those who search for this issue in the future, I couldnt make the editorconfig works but you can save the rider settings "in this computer" in the dropdown next to the save button and it will save in the file %APPDATA%\JetBrains\Rider2024.1\resharper-host\GlobalSettingsStorage.DotSettings you can't version it with git but at least you can manage your code style, better than nothing

swift falcon
#

I have a question about the video player (especially regarding 2D animation). How good is it for many animated scenes? I have concerns regarding how it manages memory compared to something like being able to preload and unload audio or even sprite animation.

rigid island
swift falcon
#

I cant really find a lot of details on how it works internally regarding that stuff.

swift falcon
#

well its about the internals of it because i need to know if i need to somehow make a script to preload each set of animations

#

vs just putting my trust into the component

rigid island
#

unity is closed source so aside from the public c# api you wont see how the actual componets are working if its C++

swift falcon
#

i know but i imagine someone must have some insight or experience with full frame animations in their projects

rigid island
swift falcon
#

ah ok thanks

steady moat
#

Not a good idea to preemptively optimize if you do not know something.

swift falcon
steady moat
#

You mean a video ? I've used it multiple time for professionnal project without any particular issue.

swift falcon
#

but im glad to hear it wasnt an issue

#

as long as it doesnt hoard the memory when i switch to a new video on the player it should be fine

steady moat
#

What is your platform ?

#

Mobile, Pc, Console ?

swift falcon
steady moat
# swift falcon mobile and PC

Be sure to transcode your video. Also, you might consider to not use video at all for mobile and instead animate in Unity.

swift falcon
wary coyote
#

What are possible reasons a List in a Scriptable Object might get its fields nulled out?
VSCode checking the field itself, its only ever added to, never set to null, new list, removed from, yet just now an entry in there I was using deleted itself

The context of the field deleting itself is that I was in play mode, exited play mode, returned to play mode, and it was gone.
I wasnt paying close attention to the field itself at the time, I was working on other things

#

It makes me greatly concerned about the stability of my project if random lists can null out like this without my input awkwardsweat

lean sail
#

If it is editor only, then you can use SetDirty to save those changes

fervent jacinth
#

im trying to make an axis independent player controller for a zero g environment, so the player can free look around and move with 'thrusters'. The problem is, whenever the player is upside down, the y axis gets inverted. heres my code:

// Update is called once per frame
void Update()
{
    if (stopped) return;

    float mouseX = Input.GetAxisRaw("Mouse X") * Time.fixedDeltaTime * sens;
    float mouseY = Input.GetAxisRaw("Mouse Y") * Time.fixedDeltaTime * sens;

    yaw += mouseX;
    pitch -= mouseY;
    //pitch = Mathf.Clamp(pitch, -90f, 90f);

    Quaternion yawRotation = Quaternion.Euler(0, yaw, 0);
    Quaternion pitchRotation = Quaternion.Euler(pitch, 0, 0);

    Quaternion targetRotation = yawRotation * pitchRotation;

    if (cameraLerp)
    {
        player.rotation = Quaternion.Lerp(player.rotation, targetRotation, drag * Time.deltaTime);
    }
    else
    {
        player.rotation = targetRotation;
    }
}```
wary coyote
fervent jacinth
#

im so sorry

lean sail
wary coyote
#

            selectedPlayActor.charData.attackMacros.Add(result);
            UnityEditor.EditorUtility.SetDirty(selectedPlayActor.charData);

Doing this now, charData is the SO

lean sail
wary coyote
clear siren
#

Uhm what mobile apps y'all suggest

ocean hollow
#

does anyone know why reordering operands will increase performance?

leaden ice
#

Multiplying a float and a vector3 is three multiplication operations

#

Your original code is doing two of the latter and one of the former

#

The new code does two of the former and one of the latter.

#

It's fewer operations and therefore faster.

ocean hollow
#

ah ok thanks

naive swallow
clear siren
#

For learning

#

I mean

vale wharf
#

Accidentally calculated chunk size wrong in my chunk visualizer in OnDrawGizmos and ended up drawing millions of gizmos causing the Unity editor to completely lock up.

Problem is, it seems the project cannot recompile the C# code. I've removed the gizmo code and saved the script but every time I enter the editor it gets stuck on drawing gizmos.

fading hull
#

Hello!
For my Unity game, I have a list of managers that are singletons containing the main game logic. These managers are organized in a prefab called "Managers." Most of these managers are static instances, allowing me to reference them from anywhere in the code. This Managers prefab gets instantiated in the Awake method when the game starts.

So far, I haven't encountered any issues with this approach. However, I'm wondering if i should look into a different approach or its fine for a solo programmer working on a small game having all this singletons with static instances (right now there is like 60 singletons for managers and there will be more probably). Thank you!

sharp bough
#

I am trying to use the Unity AI But i got these errors after installing the library. Any help?

leaden ice
fading hull
#

so wanted to know if this is fine for a smallish game or i should consider other approaches

leaden ice
#

it's fine for a smallish game

#

until or unless you run into problems

#

60 does sound like a lot, you might be making your classes too small. but other than that, if it's not causing you issues, don't mess with it

fading hull
mossy oyster
#

Hey, I have a question. For my game I created some sort of infinite road working with bezier curves that generates a list of points where the road is (I followed Sebastian Lague tutorial).
The thing is, to make it infinite, everytime you're too far away from the start of the road, it removes a section of the road and add another at the end but for now I regenerate the whole mesh (90k verts), is there a better way to do that?
Like only adding and removing tris/verts/uvs without doing something like that:
Mesh mesh =new Mesh();
mesh.verts = v;
mesh.tris = tris;
mesh.uvs = uv;
mesh.RecalculateNormals();

#

Cause generating a mesh with 90k verts and 45k tris causes a small lag spike

lean sail
mossy oyster
#

Here are all the tris

#

So yeah I kinda don't understand why it displays so many

#

And now for another road it says this

#

Ok so as soon as my car start moving, it adds more and more tris, I'll look into that, thanks for pointing that out

lean sail
mossy oyster
#

Well it looks like my cubic car is taking more and more tris to render???? If I just hide it, tris are back to normal

#

On of my trail renderer had corner vertices set to 70, don't know what that's for but it was creating 70k tris somehow

mossy oyster
lean sail
mossy oyster
lean sail
#

though tbh not sure how valid this would be in your current scenario, or if you even planned to reuse parts of the road or everything is made in a new way every single time

spare island
mossy oyster
#

So wouldn't work

#

I'll try to make the different meshes part tomorrow

lean sail
spare island
mossy oyster
spare island
#

or create them in chunks in the first place so you don't need to split them

lean sail
#

yea im not saying itll be worse, just not sure how much itll be better by

mossy oyster
spare island
mossy oyster
#

But I'll still do that, so I can have other objects (trees) attached to a road portion and delete them too when deleting the road portion

mossy oyster
idle musk
#

Is there any thing like #if UNITY_EDITOR for the windows server build? So for example #if UNITY_SERVER someBool = true #endif I'm trying to do something to make a bool true if it's a Windows Server build So ther's no confusion - the option in the build profiles section.

idle musk
#

Thanks, I do see the server one in there. Just doesn't exist for me for some reason

#

nvm I got it

#

I had to added it to scripting define symbols

#

thank you

gusty geode
#

Anybody here can help me understand why animationClip.length is returning 162 when the clip is only 3 sec long?

bleak valley
#

Hi So uh, I have this problem on my weapon script which is that when the player kills another player (that isn't him) The score doesn't get updated, But when they kill themselves (a bug that im not fixing yet) The score updates, Could anyone help me?

#

it's pretty messy so this is the one that handles giving the score when they kill a enemy

#

please ping me 5 times if you respond

bleak valley
#

a-

mossy oyster
hollow mesa
somber nacelle
#

!code and be more specific than "doesn't work properly"

tawny elkBOT
thin aurora
hollow mesa
thin aurora
#

And share the code using a paste site as mentioned above

somber nacelle