#archived-code-general

1 messages · Page 81 of 1

cosmic rain
#

Did you follow the config guide that I shared?

white moon
#

yep

small hemlock
#

oh it happens with findwithtag too though

cosmic rain
small hemlock
#

the script cant find anything out of itself

formal niche
#

that is weird

white moon
#

yep

formal niche
#

also possibly that we are just being like stupid

cosmic rain
formal niche
#

but honestly if it gets bad, maybe make a component which has a variable storing each different child you need to access

#

not sure how mcuh else i can help you here

white moon
#

from the link that provided in the guide

formal niche
#

not particularly knowledged in buildissues

small hemlock
white moon
#

to be exect microsoft

small hemlock
#

ignore the inefficiency

cosmic rain
white moon
#

i did but its not showing of 4.7.1 its only showing 7 and 6

white moon
small hemlock
#

because the entire problem seems to be that they can access anything outside their gameobject

cosmic rain
# white moon

Check the dotnet\sdk path for wether it has the 4.7.1 installed.

But honestly, I'd just use VS instead of VS code.

formal niche
#

or anythign elselike that

#

before

#

so no...

small hemlock
#

could it possibly be a bug of my editor version?

white moon
#

its not showing of 4.7.1 should i install again

cosmic rain
white moon
#

yep

#

is vs code diffrent from vs

cosmic rain
#

Alright, then you have an option to look for people that understand vs code, or forget about it and use VS instead.

formal niche
cosmic rain
# white moon is vs code diffrent from vs

Yes. Vs code is just a fancy code editor with plugins that add certain ide features. That's why it's so hard to configure.
VS is a proper ide that requires minimum configuration to work.

formal niche
#

it could be a bug, or something system specific i really dont know

small hemlock
#

i havent seen anyone else use 2021.1.16f1

cosmic rain
small hemlock
#

all right

white moon
#

@cosmic raini figured out the solution i just needed to regenrated project files in unity

swift falcon
#

This is more like a unity’s backend question

I was wondering why you cannot change an Axis directly, like position.x = 123
Is it some weird Vector stuff that doesn’t let you do that

#

I always wondered this but never knew why lol

#

Can’t find anything like that on google, or I’m just bad at searching with proper wording

west lotus
#

Because vector 3 is a struct and that means its a value type, so when you do position.x= n you are actually accessing a copy of that struct. To change a value in the original you need to reassign the whole struct.

swift falcon
west lotus
#

Its not read only it’s a full on copy, living somewhere else in memory

swift falcon
#

Oh I kinda understand

#

Didn’t know the answer is that simple

#

Thanks

knotty sun
# swift falcon Thanks

The reason that you cannot do e.g. position.x = 1; is that Vector3 position is declared as a property not a field and you can only set an entire property not just a part of it

quartz folio
#

Because a property is secretly a method, and value types are copied when returned by methods

#

so you are modifying a copy

slender basin
slender basin
#

o well let me fix that

cosmic rain
slender basin
#

thank you so much you are alife saver and its 4:00am and i can happily go bed

young hamlet
#

Hey guys, anyone knows what happened here? I reinstalled visual studio community, uninstalled visual studio code but it’s still here

#

I also reset the package managers, but the package folder will be empty, nothing inside

gray mural
#

@young hamlet is it actually the .unitypackage?

young hamlet
#

I manually downloaded Unity 2022, because my Unity hub couldn’t install it, and this one is a 3D Upr project. I didn’t do anything else😳

hollow knot
#

Is there a way i can make Everything dark in my 2D top down game? and then i use unitys built in light to make a cind of spot light which acts as a flashlight for player?

formal niche
#

delete the directional light in the scene and/or use postprocessing

#

i dont think this is in code though

young hamlet
gray mural
#

what did ya download?

gray mural
young hamlet
#

Unity 2022 installation from the official web

gray mural
#

I mean

hollow knot
gray mural
#

@young hamlet you had errors on the package

formal niche
#

yeah

gray mural
formal niche
#

there are also sprite lights

#

but honestly you can use postprocessing

young hamlet
gray mural
#

why cannot you make screenshot? i do not see anything

young hamlet
#

(01:28:18] An error occurred while resolving packages:
One or more packages could not be added to the local file syster
(01:28:19] Librarv\PackageCache\com.unity.render-pipelines.universi
mob.csi8 6reror cSOZ46: the tvbe or namespac
BurstCompileAttribute' could not be found (are you missing a using directive or an assembly reference?)
1(01:28:19) Library Packagecachelcom.unity.render-pipelines.univer
AinMax2Job.cs(8,61: error CS0246: The type or namespace name 'BurstCompile' could not be found (are you missing a using directive or an assembly reference?)
(01:28:191 Library PackageCachelcom.unity.render-pipelines.universal@14.0.4\Runtime\Tiling\ReflectionProbeMinMaxZJob.cs(8,6):errorCS0246:Thetypeornamespacename'BurstCompileAttribute'couldnotbefound(areyoumissingausingdirectiveoranassemblyreft
CS0246: The type or namespace name 'BurstCompile' could not be found (are you missing a using directive or an assembly reference?)
[01:28:19] Library
CS0246: The type or namespace name 'BurstCompileAttribute' could not be found (are you missing a using directive or an assembly referenc
012619 Librar
101:28:19 Librar Package©
CS0246: The type or namespace name 'BurstCompile' could not be found (are you missing a using directive or an assembly reference?)

#

This is part of the errors 😳

cosmic rain
gray mural
young hamlet
#

I didn't download this package, It's all default

#

Now this is a new project with same problem

gray mural
#

idk really

#

did you download VS?

young hamlet
#

when im trying to open this file, there's no default app to open.

#

Yes I have Visual Studio 2022

gray mural
#

really idk

#

don't know anything thats not about the scripting..

young hamlet
#

yea, I see, thank you, I will reinstall everything and try again

gray mural
#

maybe you wanna try to show your Visual Studio Installer?

#

@young hamlet

young hamlet
#

i only installed this for unity

gray mural
#

i mean

#

there should me no problems though

young hamlet
#

2022 and 2023 have problem to open project

#

2021 everything is fine, but now im studying a tutorial with 2022

gray mural
#

@young hamlet these?

gray mural
young hamlet
gray mural
#

@young hamlet everything is fine with 2021 version? word there then

young hamlet
gray mural
#

I also work there, new versions can be quite laggy though

young hamlet
#

I'm studying Code monkey's tutorial, he recommends the 2022 version, so i just follow his step, then it doesn't work..

heady iris
#

so what is your problem right now?

young hamlet
#

I even downloaded the finished project, then got the same problem.

#

The problem is some packages have error, I'll show you.

Now i'm using 2021 to set up a new 3D Urp project, everything works perfectly.

#

but if i use 2022 version to set up a new project, then i got this

#

If 2021 has the same functions like 2022, I can just 2021 then ignore this problem

heady iris
#

I remember seeing something like this exactly once (on someone else's computer)

cobalt wave
#

make a fresh project and just install the necessary packages yourself

heady iris
#

maybe hit it with Help > Reset Packages to Default

dusk apex
#

Someone in the forums suggested restarting your computer.

young hamlet
heady iris
#

ah, right, I guess that's the expected result :p

young hamlet
heady iris
#

I would give your machine a restart.

#

yeah

hexed forum
#

Hello? Is any random person here?

heady iris
#

probably.

#

ask your question.

hexed forum
#

I just wanna survey-like ask your preference, programming related

#

ah

gray mural
#

just ask, do not ask to ask or even ask to ask to ask

hexed forum
#

When you describe things, anything code or asset or file, that is used my multiple different things, do you prefer the word "common" or "shared"?

#

Or even "universal"?

young hamlet
#

restart already, the same. I spent almost a whole day for this yesterday...

peak halo
#

Hey, I just encountered the weirdest bug I've ever seen since I started game dev. So I have this storage UI system that allows the player to simply drag an item from one storage to another. The system is quite straight forward, it removes the item from one, adds it to another then reinitializes both. And in most cases it works fine. But sometimes, super inconsistently, it just skips the part where it adds the item to the other storage. It's not because of some if else statement, it just straight up skips a line. I tried debugging, and when I tried debugging, it fixed the issue. When I removed them or added another line somewhere else, or simply tried adding documentation between the lines. It broke again. Then it magically got fixed after playing with the comment lines again. But then reappeared in the build.

This bug is just driving me nuts. Any idea why could this be?

I tried everything, I mean probably not everything but I tried everything I can think of... Debugging, play testing with other things, trying out other ways of approaching, going through every single line... but I just cannot see a pattern. It just seems totally random... Will share the code if necessary but I don't think it will make sense as it's just a small part of a rather complex system of many scripts.

Thanks!

hexed forum
heady iris
gray mural
peak halo
heady iris
#

If it seems to change when you mess with the layout of the code/add debug statements, then it's probably just some kind of inconsistent behavior that happened to occur

#

I've definitely run into situations like that

peak halo
heady iris
#

no, !code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

hexed forum
# gray mural in what context?

For example when you wanna give name to a folder that holds very simple sprites like square or circle; would you name that folder "common sprites" or "shared sprites"?

peak halo
# heady iris no, !code

would you rather the whole script or only the method that handles the relevant part? It's quite chunky.

heady iris
#

if you're fine with sharing the entire script, you can share the entire thing

#

just tell us where the problem portion is

peak halo
#

alright

peak halo
#

in a sec

#

lmao

heady iris
#

I would lean towards "common"

#

"shared" makes me think of "shared library", which is strictly a code thing

gray mural
hexed forum
# gray mural `#Prefabs` if I use them

No I mean in a very generic way not specifically prefabs. It could be like scripts that are used by multiple things like "wheel.cs" is used by both "car.cs" and "gamingChair.cs"

peak halo
#

@heady iris https://gdl.space/ikegasehox.cs
The problem seems to be in SwitchDrawer(Item item, StorageUIElement fromStorage, StorageUIElement toStorage) Line 243: storageDrawer.Storage.AddItem(item, false);

hexed forum
#

Default?

gray mural
#

yep

#

for me, yes

heady iris
#

i would only call something "default" if it is actually a default

#

the thing that gets used if you don't specify something else

hexed forum
#

Hmm, maybe I'm not good at English but does

#

yeah

heady iris
#

a folder full of sprites that many things use is not a "default"

gray mural
hexed forum
#

i know I'm just

heady iris
#

the names do not matter

gray mural
hexed forum
#

you know what, bye

peak halo
heady iris
#

so, what makes you think that line is getting skipped?

gray mural
peak halo
#

The debug lines

#

will record a video showing it's inconsistency, is that okay?

#

will take a few minutes.

peak halo
# heady iris so, what makes you think that line is getting skipped?

What I did was; I put a debug.log line checking if the item is actually being added to the storage. In most cases it returned true, which meant that it actually worked but sometimes, it returned false. The AddItem Function is pretty straightforward. it just adds the item to the storage.

#

hold on got an idea where the problem can be. Going to investigate and report back.

heady iris
#

I'd need to see the definition of AddItem.

heady iris
#

it doesn't tell you if the item actually fit or not (:

fallen crow
#

Anyone experienced with networking, espexially mirror? Im getting really desperate over a seemengly simple problem

heady iris
fallen crow
#

Oh okay!

peak halo
# peak halo yep seems like I found the source

It seems like it cannot fit item in storage. The reason I missed this seems to be that the fit item function actually prints something out when it cannot fit item but it seems like that was on another overload. Thanks a lot!

#

Now will investigate why it thinks that the item cannot fit!

peak halo
heady iris
#

there ya go

#

rubber-duck debugging works (:

#

trying to explain exactly how your code works can help you find problems

peak halo
#

Right!

#

While you have a big chunk of my code, how readable or how good quality is it? I don't really have a chance of getting feedback on my code as I am quite isolated. I am just one dude working on a project. So don't have a teammate that can tell me if my code is shit.

#

Would really appreciate some feedback!

#

@heady iris but I still don't get why adding debug lines would change the result. Is it simply that the results are random and I am just delusional or is this a thing that can actually happen?

heady iris
#

It's probably randomness, yes.

#

I swore that adding debug statements was affecting the behavior of the program once

#

but i'm pretty sure it was just because one of my components was grabbing a reference to another during OnValidate, resulting in surprise behavior changes

peak halo
#

ah

heady iris
#

something was fluttering between being null and non-null

dusty tinsel
#

hi, I'm working on a simple ability system but there is a bug that I can not fix and I don't even know what causes it in the first place.
so with using any ability, you will lose an ability point. there are two abilities that I implemented currently: dash and double-jump.
it is perfectly fine in unity but when I build the project, the dash costs 2 or more ability points per use.
can anyone help? (I'm using the new input system btw)

private void OnAbility(AbilityType type)
    {
        if (abilityAvailability[type] == false || abilityPoints <= 0) return;

        bool condition = false;

        switch (type)
        {
            case AbilityType.DASH:
                condition = _controller.CanPlayerDash();
                break;

            case AbilityType.DOUBLE_JUMP:
                condition = _controller.CanPlayerDoubleJump();
                break;
        }

        if (condition)
        {
            GameEvents.instance.OnUseAbility(type);
            abilityPoints--;
        }
    }
heady iris
#

well, show us how you trigger that function with the input system

dusty tinsel
#
public void Awake()
    {
        input = new MainInputAction();
        input.Main.Enable();

        input.Main.Dash.performed += (context) => SendAbilityInput(context, AbilityType.DASH);
        input.Main.DoubleJump.performed += (context) => SendAbilityInput(context, AbilityType.DOUBLE_JUMP);
    }

    public void SendAbilityInput(InputAction.CallbackContext context, AbilityType type)
    {
        if (context.performed) abilityInput?.Invoke(type);
    }

this is my scriptable object input class

_input.abilityInput += OnAbility;

and this is a line of my awake function in AbilityManager class

steady moat
# peak halo While you have a big chunk of my code, how readable or how good quality is it? I...

Overall, it seems pretty good. Here a list of comments that you could consider.

  • Use [SerializeField] instead of public variable.
  • Use [Tooltip()] Instead of comments on serialize field.
  • Keep consistency in your ordering of function base on qualificator. (Public/Private/Static/Protected).
  • Use Private qualifier instead of not putting one.
  • Consider removing unused code instead of commenting them. Version Control is there for that.
  • Consider an interface for the Input instead of directly calling Input.GetMouseButtonDown(0)
  • Do not use static if the object is a Singleton.
  • Review public static void SwitchDrawer(Item item, StorageUIElement fromStorage, StorageUIElement toStorage) to not do a switch case on the type of object. Use polymorphism/inteface.
  • Create separate files for your Utility function
  • Remove obvious comment like if (!IsInteractable) return; // Return if this drawer is not interactable.
heady iris
#

^ and yes, that last point is especially important to me

#

a comment should be used when there is something unusual

#

something that is not self-evident from the line of code

#

or when you need to describe a higher-level idea that wouldn't be clear from the code

#

or when you want to apologize to your future self 🫠

#

i have been hit by at least one of these "sorry, future me" comments

dusty tinsel
heady iris
#

have you tried logging to see if the ability function is getting called twice?

dusty tinsel
heady iris
#

ah, I see

#

You can look at the player logs.

#

i'm not sure what would be causing this..

languid pilot
#

Is there a way to make preset for collider? Im picking random sprite for an object to avoid and the sizes isn;t the same. Should I make more objects or there is a solution to make collider to be picked with sprite?

dusty tinsel
rotund burrow
#

how do i visualize box cast on button press?

somber nacelle
rotund burrow
#

thanks this will be useful

wise arch
#

I am looking to generate an UI like the screenshot. I will have between 2-4 local players. What is a good approach to generate this UI?

#

I should probably add that with generate I don't mean making all UI from code, just what is a good way to only show or instantiate parts of the UI that is necessary

#

and if possible have a template that I can instantiate and by tweaking some values have different values and colours tied to it

ancient sail
#

For some reason the less frame rate the higher character jumps, even tho all my physics are in FixedUpdate and values are generated by Update and IEnumerator with WaitForSeconds

#

Im starting to lose it

split wedge
#

Anyone who knows how to fix this?

wise arch
#

Can you show the start of your file?
First 10-30 lines should suffice I think

split wedge
#
using UnityEngine;

public class AudioTestScript : MonoBehaviour
{

    private AudioSystem audioSystem;

    private void Start()
    {
        audioSystem = FindAnyObjectByType<AudioSystem>();
    }

    private void Update()
    {
        // Test if audio system can control a single source
        //audioSystem.PlayFirstWithName("SingleSource");

        // Test if audio system can coordinate multiple sources
        //audioSystem.PlayAllWithName("MultiSource");

        // Test if audio system can play random source from a collection
        audioSystem.PlayRandomWithName("MultiSource");

        // Test perception of sound created via audio system (participants needed)
    }
}
#

I first got this error when I created this file.

wise arch
#

Don't you need a using directive for AudioSystem?

Peculiar error, it says something about Unity UI which is not present

split wedge
#

'AudioSystem' is a script I created myself btw.

wise arch
#

Ah okay nvm

split wedge
#

Not sure what it is either, looked it up on the forums and most point to something with VS2022.

wise arch
#

you can always try and reboot vs2022

gray mural
#

hey

gray mural
#

ah

#

you are in fidedUpdate, i see

#

@ancient sail would you like to share your code then?

split wedge
ancient sail
gray mural
#

it's better for you to send it whole

wise arch
gray mural
#

@ancient sail !code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

rotund burrow
heady iris
#

"and then i can't see my objects" meaning that the game view goes blank?

rotund burrow
peak halo
# steady moat Overall, it seems pretty good. Here a list of comments that you could consider. ...

Hey! Thanks a lot! Got a few questions though...

  • Use [SerializeField] instead of public variable.
    Does it make that big of a difference? I find it easier to read.
  • Use [Tooltip()] Instead of comments on serialize field.
    I previously used Tooltip a lot but I felt like it was better to do it by commenting because easier to read from the code and I usually check what they are through code and not from the inspector. And kinda makes it harder to read from the code.
  • Keep consistency in your ordering of function base on qualificator. (Public/Private/Static/Protected).
    Didn't exactly get this one :))
  • Consider removing unused code instead of commenting them. Version Control is there for that.
    I left a bunch of stuff commented because I was still in the precess of building the code and wanted to have the older version there so I can copy from it and all but will remove them when I'm done!
  • Review public static void SwitchDrawer(Item item, StorageUIElement fromStorage, StorageUIElement toStorage) to not do a switch case on the type of object. Use polymorphism/inteface.
    Didn't get this one either :))
  • Create separate files for your Utility function
    I already do have a Utility namespace with a bunch of classes but these ones are only used for the StorageUI, but creating another one for everything storage UI related actually sounds good.

Thanks a lot for the feedback. Will do the rest of your suggestions :))

gray mural
gray mural
rotund burrow
#

this happens after i stop the game so i dont know how you can destroy anything then

peak halo
dark forum
#

is there a thread on here if im looking for game devs to build a mobile game?

gray mural
#

@peak halo

  • Keep consistency in your ordering of function base on qualificator. (Public/Private/Static/Protected).
    => it's nice when you write private or public for fields, do not just let is protected
private bool nice;
private bool nice;
bool nice; = protected bool nice;

=> also use static and readonly fields in case you will never change them

tawny elkBOT
dark forum
ancient sail
gray mural
#

what?

peak halo
gray mural
cobalt wave
ancient sail
cobalt wave
#

yes

#

but

#

I'd like to see the code

ancient sail
#

I only edited the part where my issue is

#

all the variables are working properly, I checked it multiple times

cobalt wave
#

wait nvm

#

my bad

#

it's a very confusing architecture

ancient sail
#

if you mean this one it just stops vertical velocity first
rb.velocity = new Vector2(rb.velocity.x, 0);

steady moat
# peak halo Hey! Thanks a lot! Got a few questions though... > - Use [SerializeField] inste...
ancient sail
gray mural
cobalt wave
steady moat
cobalt wave
#

yes, but it exists for a reason

#

so you don't have to write so much unclean code

peak halo
steady moat
steady moat
peak halo
ancient sail
steady moat
peak halo
gray mural
peak halo
#

or not.

#

I just don't get the static variables should never be changed part

steady moat
steady moat
# peak halo

It means to fully qualify the variable. If it does not change, make it readonly/const.

cobalt wave
steady moat
# peak halo why?

Because it favorize high coupling which is generally not a good idea.

cobalt wave
#

they are called in Update()
last a set amount of seconds
which can be a different frame count
the whole system is really really weird
@ancient sail

#

i'd suggest just using AddForce instead

#

and let unity handle these things instead of reinventing them wrongly

heady iris
#

however, I do agree that the example shown there is very confusing

#

it seems like things are arbitrarily either part of the public interface or kept private

ancient sail
steady moat
#

@ancient sail, you need to increment the velocity, not override it when you jump.

steady moat
steady moat
#

There is also the usage of local function for things like recursively.

heady iris
#

a class should perform all of the tasks necessary for the concept the class represents

steady moat
#

Which means, it should not have blocks of code that have significative higher cohesion together than the rest of the class.

#

That being said, in practice you might find yourself a bit more relaxed on the principle. If you absolute needs to do that, make #region in code.

heady iris
#

it's a guiding principle, yes

#

if I have an inventory class, then some functions will need to be able to find the index of an item in the inventory list, and others will not

#

it would be patent nonsense to cut the inventory class in half because of that

#

i agree that you should probably split a class up up if it has two very obvious different roles that it's juggling

steady moat
#

Not sure I understand your example.

heady iris
#

some public methods will depend on that, and others will not

steady moat
#

You put in the private section of your code. This is a capacity.

#

Suppose that you have multiple public methods that depends on it

#

Where you put it ?

#

Suppose that you have multiple public methods that depends on multiple private methods, how do you organize ?

#

There is no way to keep the code coherent.

heady iris
#

If there are several public methods that all depend on the private method, then I will, indeed, punt it to the end of the class definition

#

or, at least, to the end of that group of public methods

#

it's essentially the order I'd have written the functions in

DoesntUsePrivateA
UsesPrivateA
UsesPrivateB
UsesPrivateC
PrivateThing
DoesntUsePrivateB
steady moat
heady iris
#

I can see the value in just sorting by visibility, though

heady iris
heady iris
#

yeah, that's fair enough

steady moat
#

So, you need to constantly reorder your method.

lucid crow
#

Using JsonUtility. so i have a debug.log for saving and loading it seems to save right but loading after the game closes it doesn't do right. ill send the code for the entire game.

https://gdl.space/iqefatewum.cs -PlayerData Script
https://gdl.space/bedaqebiga.cs -GameManager Script
https://gdl.space/foxuyoquna.cs -MenuManager Script
https://gdl.space/juludoxeco.cpp -JsonSaving Script
https://gdl.space/uxipukidoq.cs -Restart Script
https://gdl.space/oyokovugub.cs -SpringMovementController Script
https://gdl.space/awafetuxem.cs -ScoreManager Script

thank you for any help you can provide! 🙂 ik this is prob alot lol

heady iris
#

you need to narrow the issue down

#

it's very impractical to analyze the entire game

#

what is wrong? does the game not write the .json file correctly?

#

does it not read the .json file?

#

does it write and read the file, but not load any data?

lucid crow
heady iris
#

okay, so it is writing the .json file

lucid crow
#

yes i is

heady iris
#

so, test if it's reading the file

#

write to the console when you hit that part of the program and check if it's getting data

lucid crow
#
 public void LoadData()
    {
        Debug.Log("Loading data");
        using StreamReader reader = new StreamReader(path); 
        string json = reader.ReadToEnd();

        PlayerData data = JsonUtility.FromJson<PlayerData>(json);
        Debug.Log(data.ToString());
    }
heady iris
#

that function does nothing

lucid crow
#

debug.log it loads the highscore value in the debug i just dont think its setting it right

heady iris
#

it reads a file, creates a local variable calld PlayerData, loads data into the variable, logs it

#

and then quits

lucid crow
#

yea so i need to set the logged variable to gamemanager highscore value

heady iris
#

you need to do something with data, yes.

glossy basin
#

Hello there, I got a question about job system, how can I call a job after lets say 1 second? I'm making a voxel game which currently generates chunks in parallel with an IJobParallel for, its very fast, however it loads instantly whenever the whole job task has finished, so it leads to a small stuttering at first

heady iris
#

sounsd like a timeslicing thing

glossy basin
#

I would like to load each chunk progressively in order to have an smooth experience (same way minecraft does)

heady iris
#

if you have a giant array of data representing chunks, just load a fixed number of chunks per update

glossy basin
heady iris
#

You could use a coroutine, yeah, or just advance by, say, 100 chunks every Update

#

I guess the ideal setup would be to sort the chunks by distance to the player, then process a fixed number every update

lucid crow
#
 public void LoadData()
    {
        Debug.Log("Loading data");
        using StreamReader reader = new StreamReader(path); 
        string json = reader.ReadToEnd();
               
        PlayerData data = JsonUtility.FromJson<PlayerData>(json);
        Debug.Log(data.ToString());

        GameManager.Instance.highScore = data.highScore;
    }
}
glossy basin
lucid crow
# lucid crow ``` public void LoadData() { Debug.Log("Loading data"); usi...

so i did this and i see where it saves it and reads it right for debug.log after i close the game now i need to set it to show on mainmenu highscore..

using TMPro;
using UnityEngine;

public class MainMenuManager : MonoBehaviour
{
    [SerializeField] TextMeshProUGUI _highScoreText;

    private void Start()
    {
        var highScore = GameManager.Instance.highScore;
        _highScoreText.text = "HighScore: " + highScore.ToString();
    }
}
worn bridge
#

Hello ! I need some help to make my tank work correctly... I have a video of the problem but basically I'm making a tank game and the tank won't go up on any kind of hill.... Any idea on how to fix ?

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

public class tankController : MonoBehaviour
{   
    public Rigidbody rb;
    public float speed = 10f;
    public GameObject shootPrefab;
    public Transform shootPoint;
    public float fireDelay = 0.16f;
    public float lastFireTimestamp = 0;
    public Vector3 velocity;
    private float verAxis = 0f;
    private void Update()
    {
        verAxis = Input.GetAxisRaw("Vertical");

        velocity = transform.forward * speed * Input.GetAxisRaw("Vertical");

        if (Input.GetButton("Fire1") && lastFireTimestamp < Time.time)
        {   
            lastFireTimestamp = Time.time + fireDelay;
            GameObject currentMissile = Instantiate(shootPrefab);
            currentMissile.transform.position = shootPoint.position;
            currentMissile.transform.rotation = transform.rotation;
            currentMissile.GetComponent<Rigidbody>().AddForce(transform.forward * 5000f, ForceMode.Acceleration);
        }
    }
    void FixedUpdate()
    {
        performMovement();
    }
    void performMovement()
    {
        rb.AddForce(velocity, ForceMode.Acceleration);
        if (Input.GetAxisRaw("Horizontal") != 0)
        {
            rb.MoveRotation(rb.rotation * Quaternion.Euler(new Vector3(0, 2 * Input.GetAxisRaw("Horizontal"), 0)));
        }
    }
}
heady iris
lucid crow
#

yes

heady iris
#

and that's where the high score is stored, right?

lucid crow
#

it shows in the debug

#

yes for between scenes

steady moat
worn bridge
glossy basin
lucid crow
#

i just got to set it to the ui. i feel that is what the mainmenu script is currenetly doing so kinda confused it should be pulling the value from gamemanager

steady moat
glossy basin
worn bridge
worn bridge
steady moat
glossy basin
worn bridge
worn bridge
#

goes at insane coordinates

glossy basin
steady moat
#

Did you manage to make a simple vehicle ?

worn bridge
glossy basin
worn bridge
worn bridge
glossy basin
#

try settinp up a basic vehicle controller with wheel colliders

steady moat
#

Did you manage to make a simple vehicle with Wheel Colider ?

steady moat
#

Start there.

worn bridge
glossy basin
worn bridge
#

as I do not really want to realistic physics

heady iris
#

there is a specific Wheel Collider type

worn bridge
#

I know

steady moat
#

You do you.

worn bridge
#

Thanks for your solutions

#

I will try both and tell you back

subtle jungle
#

is there a way i can find multiple transforms by finding them using the tag "SpawnPoint"

worn bridge
#

You take each instance and for each you take their transform and add it to an array

grizzled bronze
#

any ideas what would be causing this error?

heady iris
#

well, what is the error?

gray mural
#

yes

heady iris
#

ah, it's underlining public

grizzled bronze
#

CS1002

heady iris
#

no, that's just the error code

#

you always want to provide the full text of the error.

grizzled bronze
#

how do i find this?

#

im very new

gray mural
#

I guess you already have script with that name
Definitely!

heady iris
#

it's a syntax error; I can see it

#

click down here; that should open the Problems window

grizzled bronze
gray mural
#

ahahahah

#

ah

#

there is no ";" after namespace

heady iris
#

indeed

gray mural
#

I did not even see it

heady iris
#

The error will flag the text that confused the parser

#

So if you wrote this:

gray mural
#

forget what I have just said

grizzled bronze
#

ooohhh

heady iris
#
public float foo
public float bar;
grizzled bronze
#

I see it now

heady iris
#

the parser reads "public", "float", "foo"

#

it now wants to see a semicolon

grizzled bronze
#

thanks lmaooo

heady iris
#

but it sees "public" next

#

so it bails out and marks that as the error

grizzled bronze
#

its after the "using UnityEngine.Audio;"

gray mural
grizzled bronze
#

I missed the ;

heady iris
#

so yeah, the error will point out the spot right AFTER the missing semicolon

#

ye

grizzled bronze
#

yeye

#

ty ty

#

many more embarrassing mistakes where that came from

lucid crow
#

so think the gameManager need to load highscore from player save data for the mainmenuManager to read it and set it. becuase in the inspector the gamemanager after a restart of the game (pressing play and stop playing) it resets to 0.

heady iris
#

it's the one that knows the old highscore, after all

lucid crow
#

ok so jsonsaving should set it in gamemanager when pressing load hmmmm okay so there is the problem then its not setting it when loading still

#
 public void SaveData()
    {
        highScore = GameManager.Instance.highScore;
        playerData = new PlayerData(highScore);

        string savePath = path;
        
        Debug.Log("Saving Data at " + savePath);
        string json = JsonUtility.ToJson(playerData);
        Debug.Log(json);

        using StreamWriter writer = new StreamWriter(savePath);
        writer.Write(json);
    }

    public void LoadData()
    {
        Debug.Log("Loading data");
        using StreamReader reader = new StreamReader(path); 
        string json = reader.ReadToEnd();
               
        PlayerData data = JsonUtility.FromJson<PlayerData>(json);
        Debug.Log(data.ToString());

        GameManager.Instance.highScore = data.highScore;
    }
#

there is save and load functions of the Jsonsave script

red scarab
#

I've got multiple Prefabs based on the same base class which requires a sprite. The problem is, some of my sprites are 2x2 and others are 3x2 in size. Is there a "best practice" for dealing with this? As in, how should I go about "centering" the sprites in the Prefabs so they align with the tile grid? Alternatively, is there a way I should be slicing sprites that isn't this? Should I keep all 2x2 sprites in one file and all 3x2 in another?

lucid crow
#
 //Start is called before the first frame update
  void Start()
   {
        CreatePlayerData();
        SetPaths();
   }

    private void CreatePlayerData()
    {
        highScore = GameManager.Instance.highScore;
        playerData = new PlayerData(highScore);
    }

i think this is the issue?

#

it still loads the value tho from the savedata file so idk haha

heady iris
#
    public void LoadData()
    {
        Debug.Log("Loading data");
        using StreamReader reader = new StreamReader(path); 
        string json = reader.ReadToEnd();
               
        PlayerData data = JsonUtility.FromJson<PlayerData>(json);
        Debug.Log(data.ToString());

        GameManager.Instance.highScore = data.highScore;
    }
#

the relevant part

#

this looks fine

#

now make sure this runs before you use GameManager.Instance.highScore anywhere

lucid crow
#

can i put loaddata method used in the Jsonsaving script in GameManager for it to run on awake?

heady iris
#

It would be reasonable, yes.

#

the game manager's first order of business is to load save data

lucid crow
#

thought so

heady iris
#

assuming the game manager isn't recreated when you change scenes, of course

#

then you'd load your save every time

lucid crow
#

idk how to implament it. no it doesnt its got a singleton

#
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;
    public int highScore;

    // Awake is called when the script instance is being loaded
    private void Awake()
    {

        //Singleton Pattern
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }

        else
        {
            Destroy(gameObject);
        }
    }
}
#

right now the save data and load data metheds are called by pressing S key and L key.

heady iris
#

you can probably just make the entire load function static. it reads a file and sets some values on the GameManager.

#

I guess it reads path from that JSONSaving class

lucid crow
#

yea it makes an error 😛

#

the data is there like its ok if it doesnt load instantly i press load and it will show from the last game the highscore so even if i press load somthing is not pulling it to write it in the ui

#

in console it shows

#

its over my head for sure haha

#

wait i got it i had it //

public PlayerData (int highScore)
  {
like this- //highScore = GameManager.Instance.highScore;
       this.highScore = highScore;
   }

  public override string ToString()
   {
       return $"{highScore}";
   }
}

removed the comments and it worked. i did that at one point because of an error

#

so it loads it now

#

mb

lucid crow
sleek grail
#

Hi there, I have a maze renderer script which runs at the start of the Start Game scene. I'm making an infinite maze runner so when the win tile is touched, the scene is called again so a new maze is generated. How do I go about making the maze bigger every time? - So increasing the Maze Renderer scripts Width and Height attributes every time the scene is called

reef lagoon
#

would this script work to save the three variables for other scenes?

#

cause I wanna keep the variables of these objects and have the values that get changed for next level

hexed pecan
#

If they are DDOL then there should be no problem

reef lagoon
#

i have this in the player

#

and I have this object refrenced in "GameObject player"

#

but it still disappears

fervent furnace
#

the DDOL gameObject cant be child of other gameObject

reef lagoon
#

it worked ty!

gray mural
#

does anybody know if I need to use Time.deltaTime with rigidbody.AddForce?

mellow sigil
#

No, you shouldn't

gray mural
#

why?

mellow sigil
#

and this.gameObject and gameObject are the same thing

gray mural
mellow sigil
#

because forces already take deltatime into account, if you add it yourself then it gets added twice

gray mural
#

thanks

heady iris
#

although, amusingly, the example on the page is kind of bad

heady iris
#

it uses the default forcemode to do a jump

mellow sigil
#

yes

heady iris
#

AddForce with the default force mode tells the game how hard the thing is being pushed

#

the amount of force being applied does not depend on the timestep

gray mural
#

thx

#

what's Time.deltaTime if there is 60 fps, btw?

#

0.6f?

heady iris
#

no, it's the amount of time that passed since the last update

#

unless you use it in FixedUpdate; then it gives you Time.fixedDeltaTime

#

at 60 fps, deltaTime is 1/60f

#

fixedDeltaTime will be whatever the project is configured to use (0.02f, by default)

maiden fractal
heady iris
#

true

maiden fractal
#

But the names suggests you how how its meant to be used (impulse for singular impulses, VelocityChange for changing velocity)

gray mural
#

transform.Translate(Vector3.forward * Time.deltaTime);
so, in this code, if there are two players with 30 and 60 fps, then their position equals just every one second?

heady iris
#

their position will go up by [0,0,1] every second

gray mural
#

yes

#

and at the first frame it's gonna be Vector3(0, 0, 1 + 1/30) for 1st player and Vector3(0, 0, 1 + 1/60) for second player?

heady iris
#

yes

gray mural
#

nice then

heady iris
#

oh, yes :p

gray mural
#

oh, I mean Vector3(transform.position.x, transform.position.y, transform.position.z + 1/30)

shell scarab
gray mural
#

In my game I have enemies and player, both sides have rigidbody

If enemy collides with the player, then the player is repelled in the opposite direction

How do I make the player not being repelled, without changing it's mass?

Both enemy and player have the same Physic Material btw.

shell scarab
#

so you want the player to pass through the enemies?

gray mural
lean sail
#

Mass is the calculation used to determine how objects get moved in rigidbody calculations

gray mural
lean sail
#

Mass does not affect gravity, just change the mass

shell scarab
gray mural
#

oh

#

sorry, I mean mass, not gravity

#

Rigidbody.mass

shell scarab
#

I'm still a bit lost on what you want to happen and what is happening

#

what do you mean by repelled

gray mural
#

idk, my english might be bad

#

like

#

moves in the direction, where the player collides with enemy

shell scarab
#

so you want the enemy to stop the player from moving instead of being pushed around?

gray mural
#

enemy pushes him away

shell scarab
#

how are you moving the enemy?

gray mural
shell scarab
#

try increasing the mass on the enemy so the player can't push them

lean sail
#

Why not change the mass though?

#

Mass doesnt affect gravity, it will still fall the same way. You just need to adjust for mass if your force uses mass

lean sail
#

yea, if the force they use, uses mass, then account for it

gray mural
#

ah

#

i actually realised that I shouldn't do chat, because enemy won't collide with player, when I change my scripts

#

@shell scarab and @lean sail, sorry for taking your time

lean sail
#

dont worry, still a learning experience. Im just browsing these channels to learn more about unity anyways

ocean river
#

can .kcl be used in unity?
its a collision file format

steady moat
hexed pecan
#

The doc example is using GetButton so it happens every physics step

worldly zealot
#

I'm rotating an object like this:

transform.Rotate(input, 0, 0);
```how can I clamp this rotation?
ocean river
grizzled bronze
#

how can i make something increase each time a certain amount of score is added right now this is my solution but im not sure what i would have to do if i wanted to say double the multiplier at 25 and then triple it at 50

#

oh wait

#

never mind im having ideas right now

gray mural
#

why does this code not delete child gameObjects?

private void ResetPowerups()
{
    foreach (object powerup in powerupDocument.transform) Destroy(powerup as GameObject);
}

powerupDocument is UIDocument btw

somber nacelle
#

you cannot cast a MonoBehaviour to GameObject, however MonoBehaviours do have a gameObject property

gray mural
somber nacelle
#

well for one you want to use Transform for the type instead of object, then it should be fairly obvious what to do from there

steady moat
gray mural
somber nacelle
#

yes i see that

steady moat
#
private void ResetPowerups()
{
    foreach (Transform powerup in powerupDocument.transform) Destroy(powerup.gameObject);
}
#

I feel you are going to be there a long time otherwise.

heady iris
#

when you iterate over them, they don't give you a specific type

#

they just say "here's an object lol"

#

however, you can just write it as Simferoce did

gray mural
#

@steady moat haha, lol, thank you, I didn't know I can just write Transform there

gray mural
heady iris
#

your problem was trying to cast to GameObject instead of Transform

heady iris
#

maybe you saw "object" and though that was like GameObject :p

#

but no

#

object is System.Object

gray mural
#

cause when I used var it showed that it's object

heady iris
#

also, UnityEngine.Object is not UnityEngine.GameObject, too

#

GameObject is way more specific

#

yeah, I also ran into that

heady iris
#

tried to do a foreach with var

#

if all you know is that it's an object, you can do very, very little

#

because that's very, very vague

somber nacelle
gray mural
#

sure, thx

vague slate
#

is there any algorithms that allow removing items from list conditionally while iterating it?

#

for example doing reverse loop

#

but only removing elements that match

somber nacelle
#

yeah, do a reverse for loop and remove the elements that match the condition you want

#

there's also the RemoveAll method from linq (turns out it's an instance method on List and not from linq) that you can pass a predicate to

vague slate
#

wait, I think I confused myself

#

for some reason I decided that I can't just RemoveAt while doing reverse loop

slender basin
#

guys idk what happened i was up all night trying to learn movement relative to camera nd i finally got it and i saved i know i saved and i loaded into my project when i woke up and its basically a completely new project , i know i saved and even if i didnt it wouldnt have brought me bac to square 1

somber nacelle
#

sounds like you just need to open your scene

slender basin
#

oh lol

#

wow im dumb

#

idk why ive never had to do that before thanks );

#

lol

rustic ember
#

Is there a limit to how many components a script can require?

leaden ice
somber nacelle
#

probably not, but if you find yourself requiring an absolute fuck load of components then your code may be way too coupled

rustic ember
#

Ahaha I was just wondering

heady iris
#

isn't it 3

#

i remember there being a limit

#

or maybe 4?

somber nacelle
#

i know the ctor for the attribute can take up to 3 parameters, but you can add the attribute to the class more than once

whole night
#
static void SetActive(Object obj, bool active)
    {
        GameObject go = null;

        if (obj is Component component)
        {
            go = component.gameObject;
        }
        else
        {
            go = obj as GameObject;
        }
            
        go.SetActive(active);
    }

I am not able to figure out what this line means

if (obj is Component component)
somber nacelle
#

the is operator there is testing to see if the object can be cast to that type and then it casts it and stores the result of the cast into the component local variable

whole night
#

oh thanks

heady iris
#

woa, you can also store the result?

#

i didn't realize that

#

nice

#

I've been following up with x as Foo

#

I'm doing a lot of casting in an inventory system, because I just say "equip this item" and then it has to decide what kind of item I asked to equip

#

i'm still not sure if i'm making a terrible decision by doing that

somber nacelle
#

depends on the c# version you're using, i can't remember which version it was added in, but it's kind of recent (at least in unity terms)

heady iris
#

e.g. melee weapon, ranged weapon, consumable item

#

each one has to go into its own list of equipped items

whole night
#

In this example for a function

public void InitPool(UnityEngine.Object prefab, int size)
``` can we put GameObject instead of Object ? or are there any usecases of UnityEngine.Object ?
#

I was trying to follow some code of FPS kit which is available on unity learn and there are various things that i dont understand now

heady iris
#

The idea of using UnityEngine.Object is that it's very vague

#

you can give it a GameObject, or a MonoBehaviour, or MyCoolSpecificMonoBehaviour

#

if you don't care about anything other than 'this is a unity object', you can just say you need a unity object

#

(note that GameObject is very specific; UnityEngine.Object is a super vague concept)

golden vessel
#

Hey, I can't find what color operations do exactly. Will 0.5* color1 + 0.5* color2 give me an average color? What does multiplying do in maths term?

heady iris
#

that will give you the result of adding half of each color's values together

#

multiplying scales them piecewise

#

r1 * r2, g1 * g2, ...

golden vessel
#

So which one feels more like the average color? adding them?

mental rover
#

the idea of an "average" colour isn't that simple - there's a whole topic of colour theory to get into with it, with various blending modes

heady iris
#

yes, this is strictly just combining their rgb values

#

L*a*b time!

golden vessel
#

k I think that's what I thought it did

heady iris
#

there are so many color spaces

heady iris
golden vessel
#

RGB is linear right?

heady iris
#

it's...

#

uhhhhhhhhhhhhhhhhhhhhh

golden vessel
#

I mean technically it seemed like it

heady iris
#

in theory, it's just red/green/blue intensity

#

an additive color model

golden vessel
#

It's not reality tho, got it

#

😄

heady iris
#

in practice, the human eye notices differences between dark things more than differences between light things

#

so there's this whole gamma curve thing

#

and oh lord it's a lot

golden vessel
#

Ho that's what those setting are for then

#

Kinda like adjusting for linearity

heady iris
golden vessel
#

Thanks for the info 🙂

hollow sluice
#

Is it possible to load an object from a scene that is not loaded?

whole night
marble halo
#

So Im trying to make it so you can pan the map camera around but for some reason when ever I click and drag it jumps away

#
    {
        camView = GameObject.Find("MapCamera"); //finds the map camera
        cmDefPos = camView.transform.position;
        canvas = GetComponentInParent<Canvas>();
        viewCam = camView.GetComponent<Camera>();
    }
    public void OnDrag(PointerEventData data)
    {
        Difference = viewCam.ScreenToWorldPoint(data.position) - camView.transform.position;
        camView.transform.position = cmDefPos - Difference;
    }```
#

Ive tried so many things and nothing works for this goddamn thing

heady iris
#

you need to record the position the mouse was in when the drag began

#

and then check how its position differs from the starting point

marble halo
#

so what event would that be

#

Oh begin drag

heady iris
#

right

#

I would record the position the map and pointer were at

#

so

#

newMapPos = oldMapPos + newMousePos - oldMousePos

#

roughly

marble halo
#

would that be in the begindrag or ondrag?

lusty lily
#

I have been working and implementing this rope syste4m for a few months now and I have gotten it to a stage that works wonderful. There is a small issue where the player will randomly detach while swinging and won't change back its rotation. Is there a way I can fix this? Thank you! https://pastebin.com/s57Xa7u4

heady iris
#

use it in ondrag

#

so, that code would show up in ondrag

#

you're finding the delta between the starting position and the current position

#

and then applying the same delta to the original map position

heady iris
#

so it will always snap to the same position, I'd expect

#

oh wait, between the touch point and the camera

#

same result, though

marble halo
heady iris
#

show your code

marble halo
#
    {
        PointerEventData pdata = (PointerEventData)data;
        oldMapPos = camView.transform.position;
        oldMousePos = viewCam.ScreenToWorldPoint(pdata.position);
    }
    public void OnDrag(BaseEventData data)
    {
        PointerEventData pdata = (PointerEventData)data;
        currentMapPos = camView.transform.position;
        Difference = viewCam.ScreenToWorldPoint(pdata.position);
        currentMapPos.x = oldMapPos.x - Difference.x;
        currentMapPos.z = oldMapPos.z - Difference.z;
        camView.transform.position = currentMapPos;
        
    }```
heady iris
#

Difference is not a difference in your code.

#

it's just the current pointer position

#

remember:

#

newMapPos = oldMapPos + newCursorPos - oldCursorPos

#

(where everything is in the same coordinate space, of course)

marble halo
#

when i try that the map goes offscreen

marble halo
#

btw the camera position starts at (45,120.4.3)

summer estuary
#

is this allowed in a coroutine? yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.Return)); it seems to not be working but it feels right to me

rotund burrow
#

I need a method like TransformPoint but unaffected by scale

rotund burrow
#

i need it to be affected by position

summer estuary
#

wdym affected by position

rotund burrow
#

TransformPoint: position, rotation, and scale

TransformDirection: rotation only

TransformVector: rotation and scale only

i need position and rotation

summer estuary
#

the position is what you input into the function

#

what exactly is your goal

#

like what are you using this for

rotund burrow
#

to see global vector coordinates in player local coordinates

summer estuary
#

that function will convert world coords to local coords

rotund burrow
#

it is affected by scale

summer estuary
#

use this one then

rotund burrow
#

it doesnt include position

summer estuary
#

wdym??

#

i'm not sure what you mean by "affected by position"

#

it is the position

#

but if you really need to involve the position another time, you can just add + transform.position to the end

rotund burrow
#

do you know how the methods work?

summer estuary
#

but like if you have a transform object and you do transform.InverseTransformDirection(some point) it will use that transform's position

summer estuary
rotund burrow
#

okay tell me then what does it mean "affected by scale". i mean if we use player. transformPoint will it mutiply the vector by player scale or what

summer estuary
#

yes that is correct

#

so if the scale is (2, 2, 2) then all the numbers will be twice as far away when you call the function

rotund burrow
#

okay so i just divide the vector by player scale then

summer estuary
#

no just use the other function

somber nacelle
#

the player's local coordinate system is affected by its scale too

#

so if you want to convert a world space point to a local space point you want it to be affected by the scale otherwise it won't actually be accurate

summer estuary
#

the local coords are affected by the parent's scale, but not its own scale, i thought

#

i could be wrong idk

rotund burrow
#

what does it mean local coordinate system affected by scale?

somber nacelle
#

i mean if a player is at scale 2,2,2 then 1 unit in its local coordinates is equivalent to 2 units of world space localposition is affected by ancestor scale

summer estuary
#

i set the scale to 2, 2, 2 and the position to 1, 0, 0 and it moved to 1, 0, 0 in world coords

#

not 2, 0, 0

#

but if i add a child to that one and set its local position to 1, 0, 0 it moves to 2, 0, 0

somber nacelle
#

ah right, but either way the methods on the transform class will do precisely what they are trying to achieve

summer estuary
#

yeah

#

but my point was that if an object has scale 2, 2, 2 and you call transform.InverseTransformDirection(some point) then the result will not be multiplied by 2, 2, 2

#

so i think that's the function waif should use if i'm understanding the goal

#

at least try it, and if it doesn't do what you want then come back here

heady iris
rotund burrow
#

yes i think it will work without the complications. i still dont understand the difference between methods though.

somber nacelle
rotund burrow
#

point direction and vector

#

i'll test them myself and find out

heady iris
#

have you tried reading the documentation

marble halo
#
        currentMapPos.x += oldMousePos.x - newMousePos.x;
        currentMapPos.z += oldMousePos.z - newMousePos.z;```
#

this worked for me

#

thanks for the help though

heady iris
marble halo
#

only on BeginDrag

heady iris
#

that doesn't make sense; I'd expect this to make the map move every frame based on the total amount of distance the mouse has moved

#

oh wait

somber nacelle
# rotund burrow point direction and vector

TransformPoint changes a point in local space to a point in world space, this is affected by position, rotation, and scale
TransformDirection changes a direction vector from world space to local space, this is directly affected by rotation
TransformVector changes the magnitude of a vector from local space to world space, this is only affected by the scale

marble halo
heady iris
#

maybe OnDrag gives you a position delta?

#

that would make a lot of sense

#

no, you'd have to read .delta for that

marble halo
#
    {
        PointerEventData pdata = (PointerEventData)data;
        oldMapPos = camView.transform.position;
        oldMousePos = viewCam.ScreenToWorldPoint(pdata.position);
        Debug.Log("old map position" + oldMapPos);
    }
    public void OnDrag(BaseEventData data)
    {
        PointerEventData pdata = (PointerEventData)data;
        currentMapPos = camView.transform.position;
        newMousePos = viewCam.ScreenToWorldPoint(pdata.position);
        currentMapPos.x += oldMousePos.x - newMousePos.x;
        currentMapPos.z += oldMousePos.z - newMousePos.z;
        camView.transform.position = currentMapPos;
        Debug.Log("current map position"+ currentMapPos);
        Debug.Log("current mouse position" + newMousePos);
    }```
somber nacelle
#

why are you even using BaseEventData for the parameters anyway? you can just use PointerEventData so you don't have to cast it

marble halo
#

ah ok

pallid fjord
#

hey anybody got a good tutorial on an monster ai that can patrol and attack you if it find you?

#

im blank right now and i have one but its not that good

marble halo
pallid fjord
#

like in those horror games that walk around an when they see you

#

they will do kill u for example

marble halo
#

I don't really know of any tutorials, you could probably search horror enemy AI

pallid fjord
#

been doing lot research

#

but still gonna try find one

heady iris
#

the concept of an enemy that walks around and then chases you isn't exactly specific to horror

#

there should be plenty of resources

#

however, if you want my own take on how to do it:

#

the enemy normally picks random locations and walks to them

#

if the player gets too close, enter combat mode

#

in combat mode, just move towards the player

#

if the player gets far enough away, go back to wander mode

soft shard
proven plume
glossy basin
# pallid fjord like in those horror games that walk around an when they see you

I guess you are looking for an AI that chases on sight and maybe wanders around. I dont have any tutorials on that, but what u essentially want to do is check the transform forward angle between the monster and you; if the anlgle is less or equal to an angle you set, then it means the monster sees you, but you will also need a raycast to check if there is an obstacle in front of the monster to perform the condition mentioned before or else, it will see you at the specified angle, no matter if there is an obstacle in front

pallid fjord
#

Thanks for the tips

#

I will check them out an see which one fits best

proper pier
#

I would like to make a list of Layermasks, how do I reference a layermask?

somber nacelle
#

LayerMask is a struct not a reference type so you can add copies of a layer mask to your list

proper pier
#

yes, that is what I want. Should I use getMask?

somber nacelle
#

i mean to get a LayerMask from layer names, yes you would use GetMask

proper pier
#

are you saying I should just take copies of the layers themselves and then add them to the list

somber nacelle
#

you haven't really said what the purpose of what you are doing is or what exactly you are trying to achieve. I provided info based on what you said which was about referencing a layer mask in a list which implied you wanted to store references to some other object's layermask variable/property in a list

proper pier
#

sorry, I used the wrong terminology, but your copy suggestion was what I needed. I was trying to reference the layermasks directly, which wasn't working.

somber nacelle
#

right you cannot reference a layermask because it is a struct which is a value type not a reference type. value types are passed around by value which means when you add it to the list it adds a copy to the list

heady iris
#

could you show what you were trying to do?

#

that might help clarify things

proper pier
#

I'm good now, dw about it. thanks tho

scenic hinge
#

Given the displacement of a vector, how would you go about adjusting the position of a nested canvas object? because whatever im doing is not working.

clear moss
#

is there any way to get pathfinding to bring the agent to the closest point possible, then stop, as stopping area stops as soon as the agent reaches the wanted area

mystic owl
#

Hello, please help me, this button is not displayed for me when using the Admob demo key, do I need to add it myself or is it generated by Admob when using a non-demo key?

cosmic rain
cosmic rain
proper pier
#

hes trying to make money

cosmic rain
clear moss
cosmic rain
#

If you want multiple agents to align nicely, you'll need some kind of group steering behavior implemented.

clear moss
cosmic rain
clear moss
#

ok thanks

iron oxide
#

anyone help

rain coral
#

NullReferenceException: Object reference not set to an instance of an object
Unity.PlasticSCM.Editor.PlasticWindow.ClosePlasticWindow (Unity.PlasticSCM.Editor.PlasticWindow window) (at Library/PackageCache/com.unity.collab-proxy@1.17.2/Editor/PlasticSCM/PlasticWindow.cs:1014)
Unity.PlasticSCM.Editor.PlasticWindow.OnDisable () (at Library/PackageCache/com.unity.collab-proxy@1.17.2/Editor/PlasticSCM/PlasticWindow.cs:183)

?

#

What is this

cosmic rain
#

If it doesn't repeat, just ignore it.

rain coral
#

ok

rain coral
cosmic rain
#

If you're not using plastic, removing the package(version control I think) might also help

rain coral
#

ok ty

glossy basin
# clear moss ok thanks

A hint for flocking and steering behaviour in a performant way is by dividing your world into cells, so instead of calculating stuff for all agents in all world space, it would only calculate stuff within a world cell, which is many times faster. You may get more information of this on Boids algorithims

summer estuary
#

is it possible to set a breakpoint that stops the code when a certain variable's value is changed? i have a variable that mysteriously changes and i can't find where in my code it could possibly be changed

cosmic rain
#

Then just resume execution and it will break automatically when the value changes.

summer estuary
#

oh awesome, tysm!

#

i will try that

glossy basin
#

Helo there, I want to know if this way of using my job is actually ineficient

#

I am calling this function over and over

#

so my concern is the result array and the dispose part of it

#

Is it way too ineficient to create and dispose an array each time?

#

I assume it is a heavy task

spiral narwhal
#

so I'm making a player upgrade system. Upgrades can be dependent on multiple previous upgrades. I'm trying to implement this system using a ScriptableObject but I'm confused on how it would work later when trying to actually fetch all of the upgrades for rendering them to a UI or applying their effects. Would I have to manually register them all or in a specific place, or is there a better paradigm to use?

scarlet juniper
#

I was busy the last few days creating some fairly difficult mechanics for my game, however ive now came to a point where 1 simple mistake can cause an infinite loop which causes freezing or unity selfpause or something. Any way how i can prevent such things? It started with a 'while' function which caused a freeze. I fixed that by implementing a break but now i stumble upon freezing without a while loop

#

And it is becoming more and more difficult because of like 15 scripts working togheter at 1 time and passing variables here and variables there trough all of the scripts. One complete mess

dusk apex
#

You'd need to provide context to get proper suggestions

scarlet juniper
#

Its pretty late ill provide some clips and scripts tomorrow while referring back to the message i send above.

rapid snow
#

hey I am having a problem with something I thought was simple. I am creating a list of bools and getting it to start with x amount of slots(4) but it is created and has no slots

List<bool> _condition = new List<bool>(4);
prints(0)

latent latch
# spiral narwhal so I'm making a player upgrade system. Upgrades can be dependent on multiple pre...

I just stick all my upgrades in individual lists and update my UI accordingly when acquiring new upgrades. As for applying their effects, you can go about recalculating and pre-caching the the ability data every time you get an upgrade, though you'd probably want to optimize it a bit if you've got much more than a handful of abilities and upgrades. And, then there's just applying the effects and calculations when being used which could lead to some performance issues when dealing with larger amounts of units. It's best to balance it around both of these if possible.

leaden ice
quartz folio
leaden ice
rapid snow
#

okay, thanks heaps. I'll try that.

spiral narwhal
#

Anything that adds additional overhead that can be forgotten isnt preferred

latent latch
#

One way or another the UI needs to know about the upgrades being added, so I'm not sure how you'd resolve that besides just refreshing the UI every frame.

weak vapor
#

anyone have advice for making a modular or polymorphic method of taking values from arbitrary value sources (floats, ints, float2's, 3's, 4's, lists of them, quaternions, etc...) and formatting them all into a 1 dimensional vector of floats?

#

right now my best guess is to have a class that maintains a list, with overloads to append it correctly for each datatype

#

and then list.ToArray() when i want the actual float array

#

since i have to clear and rebuild this list many times, im hoping to make it sensical

plucky karma
#

Would avoid using ToArray() as it cause memory allocation and produces garbage collection

weak vapor
#

i see

#

I'll definitely modify it to be a cached array of a given size then, and increase the size wen necessary

#

this means i definitely need the overload approach

#

thanks very much @plucky karma !

swift falcon
#

I was thinking of simple technique to render Directional light shadows

Basically the directional light is like a camera, and all places the camera doesnt see get shaded

Does this already exist? If it does what is it called

orchid bane
#

I have these 2 pieces of code which in my opinion must be equivalent but somewhy they aren't, could you please help me to find out why is that?

public class BodiesController : MonoBehaviour {
    private Transform _head;
    private SnakeMovement _snakeMovement;

    private void Start() {
        _snakeMovement = FindObjectOfType<SnakeMovement>();
        _head = _snakeMovement.transform;
    }

    private Vector3 movementVelocity;
    [Range(0.0f, 1.0f)] public float smoothTime = 0.5f;

    private void FixedUpdate() {
        var firstPart = _snakeMovement.bodyParts[0];
        firstPart.position = Vector3.SmoothDamp(firstPart.position, _head.position, ref movementVelocity, smoothTime);
        firstPart.LookAt(_head.transform.position);
        for (var i = 1; i < _snakeMovement.bodyParts.Count; i++)
        {
            var curPart = _snakeMovement.bodyParts[i];
            var previousPart = _snakeMovement.bodyParts[i - 1].position;
            curPart.position = Vector3.SmoothDamp(curPart.position, _head.position, ref movementVelocity, smoothTime);
            curPart.LookAt(previousPart);
        }
    }
}```
#
public class SnakeBody : MonoBehaviour {
    private static float overTime;
    private int _myIndex;
    private Transform _head;
    private SnakeMovement _snakeMovement;

    private void Start() {
        _snakeMovement = FindObjectOfType<SnakeMovement>();
        _head = _snakeMovement.transform;
        _myIndex = _snakeMovement.bodyParts.IndexOf(transform);
    }
    private Vector3 movementVelocity;
    [Range(0.0f,1.0f)]
    public float overTime = 0.5f;

    private void FixedUpdate(){
        if(_myIndex == 0){
            transform.position = Vector3.SmoothDamp(transform.position, _head.position, ref movementVelocity, overTime);
            transform.LookAt(_head.transform.position);
        }
        else{
            transform.position = Vector3.SmoothDamp(transform.position, _head.GetComponent<SnakeMovement>().bodyParts[_myIndex-1].position, ref movementVelocity, overTime);
            transform.LookAt(_head.transform.position);
        }
    }
}```
#

SnakeBody works correctly, while BodiesController doesn't

cosmic rain
#

In the first snippet you move all of the parts towards the head. In the second code you move parts towards the preceding part aside from the one that has index 0.

orchid bane
cosmic rain
#

Have very slow internet ATM, so can't view your video.

orchid bane
#

In short, works incorrectly too

faint hornet
#

is this the right area to ask a question about occlusion culling? can anyone help?

solar jolt
#

I managed to build something that allows me to blacklist folders in my build pipeline

#

chopped off about 20mb from each build so far, just a matter of finding the problematic assets for each build type and adding their paths to the blacklist

#

helps me gut out client specific content from headless servers etc.

glossy basin
plain coyote
#

is there a way to make the camera input a texture instead of a scene?
I am using camera.targetTexture to render to a texture, and using that same texture as a material to a cube in my scene.

however, the camera takes its input as the scene view, what I need is a way to make it render a texture to that target texture, and not render the scene.

#

the main reason for using the camera this way, is that it automatically rescale and workout out of the box nicely

dusk apex
#

Cameras are objects in scene. If you require it, there isn't much choice.

#

Else you could blit to convert from texture to render texture but I'm unsure if you'll get what you're wanting.

plain coyote
#
        var rt = new RenderTexture(640, 640, 32);
        Graphics.Blit(tex2d, rt); // the image I want to render to the targetTexture
        Graphics.CopyTexture(rt, cam.targetTexture);
dusk apex
#

I think you would get an error with the above as targetTexture is a property and being used for reading in the above.

plain coyote
#

alternatively, (but google did not show much on it)
how do I create and apply a material that is based on a texture?
this will remove the usage of a camera for me.

then I will basically, load the image in code, to a byte array, and just change it as needed.

dusk apex
plain coyote
#

kind of solved the issue, but I just removed the camera and created a material on the fly

rich gate
#

Hey, silly question. Does anyone know how i could decrease the probability of an object spawning when it gets further away from a position? I would like the probability to be 100% when the distance between the object and it's spawn point is 0, and 0% when the distance is 1.

plain coyote
uncut plank
#

though in this case, the probability shoulf simply be 1 - distance

rich gate
#

ok ill try it out

#

Like this?

        float chance = position.magnitude / (position.magnitude * maxSpawnDistance);
rich gate
#

actually

#

hang on

#

are you proposing this?
float chance = position.magnitude / maxSpawnDistance;

#

I suppose some more info is needed. I'm trying to affect the chance of spawning a star. I want more stars toward the center of the sphere and less toward the edge.

private void GenerateSphericalGalaxy()
    {
        for (int i = 0; i < spawnTries; i++)
        {
            //Get random unit position
            Vector3 position = Random.insideUnitSphere;
            
            //Calculate spawn chance based on distance from center
            float chance = position.magnitude / maxSpawnDistance;
            

            //Squash factor
            position.y *= squash;
            
            VirtualTransform vt = new VirtualTransform(position);
            virtualTransforms.Add(vt);
        }
    }
knotty sun
rich gate
#

Alright. Thanks for the help so far guys. Any idea how I could take that chance variable and use it to decide whether to spawn the star or not?

#

perhaps ```cs
if (chance > 50f) {
//spawn the star?
}

knotty sun
#

chance will always be between 0 and 1

rich gate
#

lol

#

oops

#

but you get my meaning

knotty sun
#

simple way

  1. Round chance to 1 decimal place
  2. Get Random number between chance and 1f
  3. round that number to 1 decimal place
    if number == chance spawn
    you could play around with the rounding to give more variation
uncut plank
#

you cant reliably use == on floats

knotty sun
#

better. multiply by 10 then convert to int

rich gate
#

sounds good. im gonna work this out. ill let you know how it went. thanks

fervent furnace
#

i believe you can simply if (chance>0.5f)

knotty sun
#

that will not give linear progression

rich gate
#

thats what i had originally

#

i accidentally typed 50 in chat

#

@knotty sun is right

#

I just tried this to no affect. ```cs
float chance = 1f - position.magnitude / maxSpawnDistance;

        float rnd = Random.Range(0f, 1f);
        if (chance > rnd)
        {
            VirtualTransform vt = new VirtualTransform(position);
            virtualTransforms.Add(vt);
        }```
chrome horizon
knotty sun
#
float chance = 1f - position.magnitude / maxSpawnDistance;
int i = (chance * 10f);
int rnd = Random.Range(i, 11);
if (i == rnd) 
mellow sigil
#

Don't cross-post

reef compass
#

ok sorry

knotty sun
#

you cannot access GameStatus using the class name you need to get a reference to the class instance

rich gate
#

@knotty sun that also didn't work. thanks though.

knotty sun
#

why not?

rich gate
#

It may work. maybe just not exactly what im going for. I'll mess around with it.

#

it's definitely working but it's not spawning enough stars. propably just have to multiply chance though

late lion
# chrome horizon Anyone know how to fix my canvas being bright 😆 https://i.imgur.com/2JvuFAr.png

This appears to be bloom, but you probably already knew that. This is why it's best to have a bloom threshold of 1 or greater. What's happening here is that the white background is probably fully white rgb(1.0, 1.0, 1.0). If your bloom threshold is below 1, that white color will always have bloom added to it. To fix this, you have to enable HDR on your camera, so that pixels can be brighter than 1. Then you can make your bloom threshold > 1.

#

Alternatively, you can also look into changing the order of your UI rendering to come after and on top of post processing.

knotty sun
reef lagoon
#

I have a question, i have a child object which has a collider that works as player collider. But a parent object has a rigidbody. The thing is that when a bullet colides with the player it collides with the parent object. Does the collider have to be in same object as rigidbody?

#

its pretty standard code that im pretty sure worked in earlier stages

limber onyx
#

anyone know how to make dotween work when time scale = 0?. i try to use .SetUpdate(true) but it not work

thin aurora
tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

chrome horizon
reef lagoon
#

How do I get rid of DDOL after player dies? I want to load menu but the player stuff comes with it.

late lion
chrome horizon
late lion
# reef lagoon any1?

You'd have to destroy it manually, by getting a reference to the objects and calling Object.Destroy on them.

thin aurora
#

If you have an object that uses DDOL, it is assumed that this object is never destroyed

#

In your case it is destroyed when the player dies

#

So, you can make your own additive scene, call it "player context scene" or something. This contains everything that must exist until the player dies or is removed. When that happens, simply unload that scene.

#

You might want to make whatever you put in it a singleton, and ensure that its instance reference is removed so that it is fully reclaimed by Unity. Note that you can't set a SerializeField with objects from another scene, hence why this is probably the best you can do. You can then reference that instance when the player exists and do whatever you want to do.

thin aurora
#

If there are dependencies between the two, you could make these split objects communicate with a parent object when it comes to retrieving shared data.

reef lagoon
#

I kind of solved it by destroying the objects when player dies

#

and for the moment it works

thin aurora
#

That's still a bit of a bandaid

marsh geode
#

Hello, does anyone know how to replicate this scaling tool (where you can scale it from the corners) in runtime?

chrome horizon
marsh geode
chrome horizon
marsh geode
chrome horizon
marsh geode
slim kite
#

Where can I find informative documentation about perlin noise generation that consists of informations and examples for each step of the generation?

heady iris
#

From where? Unity.Mathematics?

#

Or are you just asking about Perlin/Simplex noise in general?

leaden ice
#

Not sure I understand the problem but it also doesn't seem code related

chrome horizon
cosmic rain
slim kite
slim kite
uncut plank
#

some article or video

slim kite
#

Do you know any discord servers made for procedural generation or computer graphics, so I can ask specific questions there?

#

Because it seems this server is more unity focused

uncut plank
slim kite
#

I didn't see #⛰️┃terrain-3d, maybe there will be more relevant. Although I am still not expecting much knowing there's a built-in perlin noise function in unity

uncut plank
slim kite
#

They might be fine, people might just be less knowledgeable when it comes to programming outside of unity

pallid sparrow
#

Hello everyone, do you have some link to search for nfc in unity ? I already did seek Twisprite plugin, but it doesn't launch my unity activity and i would want to understand each step. (Not a frequent user of android studio for .aar)

sweet basin
#

Ok so hey everyone, I have a very simple question. I'm using the pro builder to make an appropriate map for my game, right now I'm trying to make proper walls to surround the area, but I'm able to just drag the line across the terrain rather than lock it and have it move from block to block (so that I can do it more precisely). Can anyone tell me how to switch it?

sweet basin
#

Ohh ok thank you

raw wyvern
#

If anyone here knows anything about procedurally drawing lines, i wanna write a script that draws a pixel line from the hook to the fishing rod as the hook moves. Any suggestions?

hollow hound
#

Is there a way to completely destroy gameObject?
With simple Object.Destroy() unity still saves some of the object data if there is a reference to it.
How can I completely delete object from memory even if there are references to it?

leaden ice
leaden ice
#

The only references that might remain after calling Destroy are references in your own code

heady iris
#

what is the problem that you're trying to solve here?

leaden ice
#

There is no way - in any programming language as far as I'm aware to automatically find and ... what would you even do with existing references? Set them to null? That's very destructive

hollow hound
leaden ice