#archived-code-general

1 messages · Page 187 of 1

low horizon
#

i have no idea if there is a better way

cosmic rain
#

If you have 1 SO mapped to 1 instance type, you can have something like CreateRuntimeInstance virtual method on your SO. And inside of each SO type, create the specific Runtime instance and return it.

somber nacelle
#

yeah the better option of those suggested so far would be to just use a Scriptable Object for each skill type and you can drag it in. otherwise you could use something like SerializeReference and some custom editor stuff to serialize instances of the class you need.
vertx has a SerializeReference Dropdown package that would be nice for this

night harness
#

just use a Scriptable Object for each skill type and you can drag it in

I do have a unique SO per skill, where are you suggesting I drag it?

#

oh wait, i think theres been a miscommunication

low horizon
#
    public override Type MatchingSkillScriptType()
    {
        return typeof(ScytheSlashNormalAttackSkill); 
    }
night harness
#

every skill has a unique class

low horizon
#

something like this?

somber nacelle
# night harness oh wait, i think theres been a miscommunication

i meant use a scriptable object for the behaviour, instead of using a scriptable object just to instantiate a poco. you know, like i suggested earlier
this would save you the trouble of using reflection and the Activator class to create an instance of your desired class because it would already exist

cosmic rain
low horizon
#

thanks

night harness
#

theres 1 SO type and x amount of runtimetypes

#

in my scenario

cosmic rain
somber nacelle
# night harness theres 1 SO type and x amount of runtimetypes

yes i'm aware of how you currently have it set up. at this point you're either willfully ignoring what i'm suggesting or just not getting it so i'm giving up. good luck and have fun with your reflection since you're hellbent on using that 🤷‍♂️

night harness
#

Homie ima be real

#

if your not feeling it you don't have to keep helping

#

I appreciate it but the tone is a little weird

low horizon
#

do you suggest creating an instance of scriptable object

somber nacelle
#

well presumably the instance of the SO would already exist

cosmic rain
#

Like a fireball and super fireball with double the range, damage and a fancier vfx?

somber nacelle
# low horizon what if you want to change variables of class in runtime?

of course changing the properties of a scriptable object asset works differently in the editor as opposed to a build so there would probably be a bit of weirdness from that, but that doesn't completely invalidate the suggestion. nor does it mean they still can't use a POCO for the behavior part, but they'd have that SO that already has the data they need instead of using reflection and strings to create the type at runtime

rain minnow
night harness
night harness
#

😛

rain minnow
#

isn't that normal?

night harness
#

no like

#

every type

rain minnow
#

sorry, not sure what you mean by that . . .

low horizon
#

ohh thanks

#

so a poco holds default values

cosmic rain
low horizon
#

and you don't need to insantiate the so too

#

i think i understand, thanks

night harness
low horizon
#

this seems better than using activator and dealing with types

night harness
rain minnow
somber nacelle
night harness
#

I'm doing research now! People keep responding so I keep responding back 😅

rain minnow
night harness
#

Skill is more data based (name, desc, icon etc.)

OneSkill & TwoSkill store game mechanics with completely seperate, running code

cosmic rain
low horizon
#

im kinda confused

rain minnow
night harness
somber nacelle
#

yes

night harness
#

Does that mean I need to make a copy of it at runtime or do I need to reset it's values when the game stops playing? does this instance ever die?

cosmic rain
#

Sounds like boolean mesh operation.

#

Research boolean operations on polygons.

ruby nacelle
#

Hey! I'm using A* to control enemy pathing, Just curious how to give all enemies the players transform from a prefab, whenever the player dies they also lose the instance of the transform to reference which is mucking everything up

somber nacelle
#

prefabs cannot reference scene objects and if the prefabs reference another prefab it isn't automatically changed to the instance in the scene. so you'll have to pass the reference to the player's transform when you spawn the enemies. I'd also recommend an event or something for when the player dies/respawns to update the reference. or just don't actually destroy the player but reset it's position/health/whatever instead

ruby nacelle
#

oooo thank you v much

loud oxide
#

each time I load up my unity project in omnisharp I get a lot of errors about
Analysis of document float4x3.gen.cs failed or cancelled by timeout: The operation was canceled.
This error happens for I think all of the .cs files in com.unity.mathematics@1.2.6 as well as some others. Is someone familiar with this?

torpid ingot
#

Hi guys, having a little problem with a Collider.

Trying to register when my "bullet" collides with anything.
Do I have to do anything besides attaching a CircleCollider2D to my "bullet" (and rigidbody for the physics)
and then, In a script, attached to the "bullet", use the "OnCollisionEnter" method?

torpid ingot
#

Thank you, I'm stupid!

#

I used:
OnCollisionEnter(Collision collision)
and should use:
OnCollisionEnter2D(Collision2D collision)

somber nacelle
#

you might wanna double check that resource i linked again 😉

torpid ingot
#

Oh, now Im really stupid.. thank you

#

Another question. I'm on Linux and are using VS Code. In "regular" VS, one get's a little help from Intellisense.. I think I have all extensions needed for VS Code to make it work as VS, but the color scheme and everything doesnt really work as i thought it would..

somber nacelle
#

!vscode

tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

torpid ingot
#

Sorry, I missed this, thats in the rules right? Not having a very good day here! -_-

somber nacelle
#

the IDE configuration stuff is in #854851968446365696 which is honestly probably the least read channel in the server 🤷‍♂️
just be warned that vs code can be super finnicky with unity. so if you happen to have access to Rider i'd recommend using that instead

torpid ingot
#

Oh, I'll check Rider out. Thank you very much for your input!

obtuse flame
#

Im trying to set the value of my slider to my progress variable but GetComponent seems to return null, the image shows the chargebarImageObject object
chargebarImageObject.GetComponent<Slider>().value = progress;
am I missing something here?

prime sinew
obtuse flame
#

100%

prime sinew
#

show it

#

and how do you know it's the GetComponent that's returning null

obtuse flame
obtuse flame
prime sinew
fervent furnace
#

log them both, or use debugger

lean sail
#

Is it possible that Slider is referencing a type other than the UnityEngine.UI one?

#

Otherwise I'd assume references are lost at one point

obtuse flame
obtuse flame
fervent furnace
#

try to get all the components to see what components the gameobject has.....

obtuse flame
#

i mean im also doing this and it works just fine, its the slider that doesn't want to work
chargebarImageObject.GetComponent<Image>().fillAmount = progress;

prime sinew
#

have you tried.. removing and readding the Slider? 🤷 this is weird

fervent furnace
#

so i just recommend you log all the component on that GO

prime sinew
#

you're sure this is the only object with this script in the scene? @obtuse flame

obtuse flame
#

i mean this is on my player prefab but its a multiplayer game so there will always be multiple

obtuse flame
prime sinew
obtuse flame
fervent furnace
#
foreach(Component component in GetComponents(typeof(Component))) {
  Debug.Log(component);
}
```are you using this?
obtuse flame
lean sail
#

What part is actually giving out null, we havent seen the actual error/line number tbh

#

This might just be something simple and not what we think the error is

fervent furnace
#

it doesnt have slider on it

lean sail
fervent furnace
#

you can crop the image so you dont expose it to us

jaunty needle
#

How do I bound the line between the two axes so that it snaps to one of them

#

First I thought of doing this:

    private void DisplayArrow()
    {
        Vector2 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
        Vector2 currentPos = Vector2.zero;

        //Detects if the cursor is within bounds
        if(cursor.transform.position.x <= xAxis.position.x || cursor.transform.position.y <= yAxis.position.y)
        {
            isWithinBounds = false;
            currentPos = new Vector2(cursor.transform.position.x, cursor.transform.position.y);
        }
        else if(cursor.transform.position.x >= xAxis.position.x && cursor.transform.position.y >= yAxis.position.y)
        {
            isWithinBounds = true;
            currentPos = new Vector2(cursor.transform.position.x, cursor.transform.position.y);
        }

        if (isWithinBounds)
        {
            lineRenderer.SetPosition(1, mousePos);

        }
        else
        {
            //print("outside bounds");
            //lineRenderer.SetPosition(1, currentPos);
        }

    }
#

But it's a frame too late

#

or too early it varies

#

I thought of using colliders but I couldn't figure out a way for that either

rocky helm
#

What exactly are you trying to achieve?

placid summit
#

will JsonUtility not deserialize to decimal? float or double seem fine but not decimal

late lion
#

And if you don't know the answer to that either, the answer is no, Unity doesn't serialize decimal.

placid summit
#

Yeah the manual is unclear though... mentions double and 'basic types'. Anyway seems unsupported in all cases on trying

#

ah decimal is not a primitve data type - well everyday is a learning day...

cunning thunder
#

Is there fast way to spawn bunch of those blocks and have them being simulated so they collide and bounce with ground?
These are spawned when blocks explode/trees fall down, for example.
And yes I am pooling them.

Right now the performance is ok but not so ok when there is hundreds or thousands of blocks, resulting of large explosion

#

Also right now they use box colliders & rigidbodies and I would like to keep them 3d rather than rendering them flat 2d

leaden ice
cunning thunder
heady iris
#

it's wild

jaunty needle
#

I got the detection to work but the line updates later than the detection, not on the same frame

#

The line doesn't follow the mouse exactly, it lags behind

late lion
jaunty needle
#

Goddamn that worked beautifully

hard viper
#

is there a good way to intercept the effect of an areaeffector2D so an object can only take force from one point effector of a given tag at a given angle?

#

or is that something that needs to be done via script, replacing the area effector?

leaden ice
#

But as for making temporary objects that will disappear, maybe just look into a particle system

#

Or VFX Graph

hard viper
#

does anyone know how to modify contacts? I'd like to make my own effectors to work better for my purposes.

#

or know of reference material to learn

#

alternatively, if I could get source code for effectors in Unity, that would also help tremendously

cosmic rain
leaden ice
#

Also note this has been fully released and isn't experimental anymore

hard viper
#

cool

#

ty praetor

#

my goal rn is to make an area effector that tries to avoid double counting with other area effectors tied to gameobjects of the same tag (in one frame). My next goal after that is to make a platform effector that actually works with tilemaps, so I don't need to instantiate 5000 gameobjects just to have some semisolid platform blocks.

late lion
# ashen yoke this is preprocessing?

It's modifying the contact before it's resolved, if that's what you mean. So you can, for example, tell it to ignore contacts so the colliders go through each other.

ashen yoke
#

yeah its what i mean

#

cool

violet igloo
#

How can I remake an OS like windows 95

leaden ice
grave pulsar
#

Hello, for a project I’m working on I need to track the position of a real life object and have an asset mirror the position of the real life object in real time. The idea is to have a stationary camera connected to the PC which will get the live feed of real life object’s position. I’ve been looking into Unity’s AR Foundations to achieve this but I haven’t gotten anywhere yet. I’m new to Unity and I was wondering if I’m on the correct path and what I would need to do or if this is something that has been done before and I can get a bit of guidance (from what I’ve gathered, I can’t find any similar projects on the internet)

brittle sparrow
#

this is always a sight to behold

celest moss
#

`public class LevelTransition1 : MonoBehaviour
{
public GameObject EnemyIcon;
public GameObject TreasureIcon;

public GameObject Arrow;
public GameObject Background;

public LevelManager LevelManager;

public GameObject IconContainer;

private void Start()
{
    moveArrowAboveIcon(IconContainer.transform.GetChild(3).gameObject);
}
public void ShowTransition()
{
    LeanTween.moveY(Background, 540, 1f);
}

public void moveArrowAboveIcon(GameObject EnemyIconToMoveTo)
{
    Arrow.transform.position = EnemyIconToMoveTo.transform.position + new Vector3(0, 100, 0);
}

}`

celest moss
flint sierra
dusky dune
#

guys I am having a hard time conceptualising an answer to my problem can someone help me with that please.

so what my problem is, im making a detective game and each object that has a script called clue in the script a description of the clue is made. I need to add each clue description to a JSON file. I was able to follow a tutorial on writing to a json file but it doesnt work properly because its overwriting each clue description to file. can someone please help me re write the code so that it adds each clue description the json file.

public class Input_Handler : MonoBehaviour
{
    [SerializeField]
    private Clue clue;
    [SerializeField]
    private string FileName;
    List<Input_Entry> entries = new List<Input_Entry>();
   
    public void Add_Clue_Description_Text()
    {
        string Clue_Description = clue.InteractionDescription;

        Debug.Log("Clue_Description " + Clue_Description);
        
        entries.Add(new Input_Entry(Clue_Description));
        Debug.Log("entries.count " + entries.Count.ToString());
        
        Clue_Description = "";
        File_Handler.Save_To_JSON<Input_Entry> (entries, FileName);
    }
}
``` so this class is attached to multiple objects and the problem is because they are attached to multiple objects each object has a unique array called entries and is writing to the same file so it keeps getting overwritten how can I fix this ?
swift falcon
#

Can anyone help me figure out why the Steam .NET SDK doesn't recognize any achievements?
With this code I get an output of 0 achievements despite making an achievement in steamworks:

if (!SteamManager.Initialized)
            {
                Debug.Log("Steam not initialized");
                return;
            }

            uint count = SteamUserStats.GetNumAchievements();
            Debug.Log("Achievement count: " + count);

I have Steam running and I've set the app_id in steam_appid.txt
Steam says the game is running, when I stop it, it closes Unity
SteamWorks initialises correctly, at least it tells me it does
The achievement has both icons set correctly
I've tried restarting steam/unity

Do I need to make the game public/visible in some way? I'm pretty sure I don't need to publish anything yet
I tried running it in a build as well but the same thing happened
Steam overlay is also not working but not sure if it should yet

I also call this code in Update before any achievement code runs:

if (SteamUserStats.RequestCurrentStats())
            Debug.Log("Steam stats received");
        else
            Debug.LogError("Steam stats not received");```

Hopefully someone can help me thanks

Edit:
I had to publish everything first, damn it
distant acorn
#

pls 2 d movement code

#

!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.

dusky dune
still gust
#

Hey does anyone know how to create individual logic for methods within a ScriptableObject? So for example I want A ScriptableObject containing data for each Enemy and they all have the Attack method that can be called from the EnemyController but I want to make each Attack logic different for each ScriptableObject

simple egret
#

You need multiple scriptable objects (can make all of them inherit from a base class so you have common abstract methods), or don't implement the methods in the SO, but instead expose an event that you can link to a method in one of your scripts

thick terrace
# dusky dune anyone???

you made "entries" an instance field so each time you save it only includes the object that saved it, maybe just ditch the entries field and load the existing list from the json file before adding the item and saving it back?

dusky dune
thick terrace
dusky dune
#

of type input_Entries?

thick terrace
#

a list, i guess you would have to do something like var entries = File_Handler.Load_From_JSON<Input_Entry> (FileName);

dusky dune
thick terrace
#

well atm you're saving over the content and losing the previous entries every time right? to append to the list you'd need to load then save

dusky dune
#

oh so load the file with the code you gave then do this

entries.Add(new Input_Entry(Clue_Description));

then do this

 File_Handler.Save_To_JSON<Input_Entry> (entries, FileName);

so read, write, save?

thick terrace
#

yup!

#

you could probably find more efficient ways to share the list around between scripts, but that's a simple fix

dusky dune
#

ok thx

torpid folio
#

Ok guys I need your advice and opinion about how to structure the code of a 2d Platformer in a nice way. Most of the code I find is simply a controller script that contains all movements in one script such as horizontal movement, jumping, falling,etc.
Now that is quite easy to build up, but I think the code is quickly getting messy if you have additional abilities such as dashes, double jumps and so on. In addition distinguishing between the single states is not that easy and beautiful.
Now I lost my heart somehow to using a statemachine that manages the changes from one state to another (similar to what the animator does with the transitions). Therefore each state (such as IdleState, RunningState, JumpingState, etc.) is then put into a separate script file that contains a state class. The base class methods are always executed and can perform common actions that are needed for almost any state.
But there are downsides aswell: The states of a statemachine are no monobehaviours and thus I cannot use the [SerializeField] option to configure my script easily. Also transferring data from one state to the other is not that easy.

Now my question is: Do you see a way to get rid of the statemachine downsides? What is your opinion about this? Sorry for the long explanation

ivory charm
#

I have no clue what is going on or if i am going about this right i am trying to move playerObject out a parent object. i put them in .. but this playerObject.transform.parent = transform.root; Line of code moves them out of the object i am happy with. but the Player Positioning is incorrect Will not center with the scene it created its own center.

spring creek
ivory charm
#

That what i was just thinking..

spring creek
#

Is the root object at world origin?

#

0,0,0 on your object is the position of its new parent

ivory charm
#

SetLocalPositionAndRotatio i used this line after it was moved.

spring creek
ivory charm
#

Yeah that was the issue I changed it to SetPositionAndRotatio

#

What i was trying to do is enter an object like vehicle and exit out next to the vehicle.. i moved everything including player object in to an object attached to the vehicle.

#

Let me edit this...

spring creek
#

Ok, so don't you think you want to do

playerObject.transform.parent = null;

?
Because wouldn't the root be something to do with the vehicle?

#

Then get an offset from the vehicle position for the exit position

ivory charm
#

Does that move the object out of everything. and its placed in the main scene

ivory charm
#

Haa i need to keep note of this null.. that worked even better.

#

Thanks for the suggestion

swift falcon
#

i might have experienced a bug? so i have a sound thats on and everything is setup but of some reason it isnt playing, i found out that if i right click the audio source component in the inspector it starts playing but i have no idea why, can anybody explain why?

ionic isle
#

im a 10X dev, ask me anything

dusky dune
swift falcon
teal raven
#

I learned c# fully but still I can't create my own movement script

lucid wigeon
#

Im a 0.5X dev

#

Halfdev, half human half dev

leaden ice
#

Go to the texture and make it read/write

dawn zinc
#

(2d) I'm trying to make a camera follow script and the camera goes blank because it goes into the player

dawn zinc
knotty sun
civic igloo
#

Reloading a scene in runtime completely breaks events for me, i get a missing reference exception where it's missing a reference to the script itself when it tries calling the event

using UnityEngine;
using UnityEngine.Events;
public class EnemyClear : MonoBehaviour
{
    public UnityEvent OnRoomClear;
    private void Start()
    {
        Enemy.OnAnyEnemyDeath += CheckRoomClear;
    }
    private void CheckRoomClear()
    {
        print("check");
        if (transform.childCount == 0) OnRoomClear?.Invoke();
    }
}
civic igloo
knotty sun
#

So you have something subscribed to OnRoomClear which has not unsubscribed in OnDestroy

civic igloo
#

well the only things i subscribed is a song change and turning off the lights through the inspector

leaden ice
#

so you still have a destroyed object listening to the event

knotty sun
#

Could also be a subscription to OnAnyEnemyDeath

civic igloo
leaden ice
#

but on the destroyed copy of the script

#

hence the error

#

to fix it - properly unsubscribe in OnDestroy

knotty sun
#

yes,
EnemyClear needs an OnDestroy method which unsubscribes CheckRoomClear from OnAnyEnemyDeath

civic igloo
#

alright that did it

#

thanks!

native quest
#

is there a writeup somewhere that gives guidelines on where to place specific behaviors/methods ini the update order?

#

like should my state machine checks happen at the beginning of the simulation? or at the end?

steady moat
leaden ice
native quest
#

position, velocity, cd timer

#

I'm using ECS

leaden ice
native quest
#

this logic doesn't really apply in general tho?

leaden ice
native quest
#

upadate/lateupdate?

#

fair enough

#

thanks I'll ask over there

torpid folio
torpid folio
dark kindle
#

Is is better practice to control disabling/enabling of game objects themselves or components of game objects

leaden ice
dark kindle
#

Ok thanks

merry sierra
#

is there a way to spawn heavy prefabs in scenes so that the time dont freeze or any lag like can give the preload time or something

steady moat
#

You could also divided them in smaller parts

merry sierra
#

but how u get that is it loaded or not

steady moat
#

However, you shouldnt really have "heavy" instantiated object out of loading.

steady moat
merry sierra
#

so i have only one scene so i am trying to do all the stuff in one particular scene

merry sierra
#

so basically i have multiple levels like can be 100+ so i cant really make 100 levels

steady moat
spring creek
steady moat
merry sierra
#

basically two scenes one for ui and one for all the levels?

lean sail
#

Just keep it disabled and enable the object when you need, while having it already placed in scene or spawned in awake or something

steady moat
#

You have a "first scene" that is basically empty that only has 1 objective, loading the rest of the game.

#

You then either transitionate to a MainScreen or you instantiate a UI canvas.

merry sierra
#

no that is ok but i dont want to load 100 of levels at once like the scene will be very heavy i guess

steady moat
#

Which then go to the appropriate scene whenever the user click on "Play"

steady moat
lean sail
#

Are these objects you are spawning your entire levels?

steady moat
#

That is considering that you have a proceduraly generated level.

merry sierra
#

so if instantiate a level in awake or something will it also get load if i use async ?

merry sierra
#

it should already be present in a level?

steady moat
#

However, the lag spike will be hidden.

#

And, you should load it in multiple part, given that it is proceduraly generated.

#

Otherwise, just make 100 scenes.

merry sierra
#

not doing proceduraly generated or something

steady moat
#

Then just make 100 scenes.

merry sierra
#

ok

#

size will pe hude then right

#

huge

steady moat
#

Why ?

merry sierra
#

of project like if we make 100 scenes

steady moat
#

Why would be larger than 100 prefabs ?

#

Scene a large usually because they contains more things, however in your case, the scene will be equal to a prefab

#

So, no it will not be larger in size.

merry sierra
#

got it, thanks

#

so the correct thing will be async.loadlevel right

steady moat
#

Yes

merry sierra
#

👍

steady moat
#

Also, async will only load the resource asynchronously, you will have the instantiation sync.

lean sail
#

Even if there was a difference, I think 100 scenes is way better because editing these all as prefabs sounds extremely tedious

midnight parcel
#

hello, does anyone know a better way to handle all of this? i wrote this late and forgot if there was any function (relating i think) to mathF that shortens all of this by a lot

leaden ice
#

isn't tjhis just a simple math function?

lean sail
#

Seems like the condition and return value are directly related

midnight parcel
merry sierra
#

use a loop i guess to check and return

lean sail
#

Like this is literally just subtraction

leaden ice
#

yeah it's like

return Y_Axis - boundsMaxY - 1.54f;``` or something
midnight parcel
leaden ice
#

i mean I didn't think that hard about that formula but it's basically something along those lines

#

what you hve no is definitely going to not be as smooth as this (assuming this math is correct)

midnight parcel
#

i'm gonna try that out rq and check if theres anything else to smooth it out

midnight parcel
spark flower
#

what was the syntax of running a function if a bool is true

#

it involved =>

#

something with L ?

somber nacelle
#

huh? you just use an if statement to check if the bool is true or not before calling the method

leaden ice
#

the => is lambda expression syntax

spark flower
#

yes lambda

leaden ice
#

which ... does not do what you said

#

I think there's probably some missing context here if you are associating lambdas with that

spark flower
#
        Interactable _int = other.GetComponent<Interactable>();
        if (_int != null) { _int.Interact(this); }
    }```
#

i want to turn this in lambda

somber nacelle
#

why

#

also just use TryGetComponent then you can combine the getcomponent and null check into one line that goes right into the if statement

spring creek
jaunty needle
jaunty needle
#

I have zero idea why it's not showing here wtf

#

No not that

#

bruhh

#

Here

#

Game view

leaden ice
#

one thing is that UI/Canvas space is not the same as world space

jaunty needle
#

Yes but it's working here fine:

    void SetPositionAtMidpoint(Transform toMidpoint)
    {
        Vector2 origin = arrowShower.lineRenderer.GetPosition(0);
        Vector2 currentLineEndPos = arrowShower.lineRenderer.GetPosition(1);

        Vector2 midPoint = (origin + currentLineEndPos) / 2f;

        toMidpoint.transform.position = midPoint;
    }
leaden ice
#

unless you're using Screen Space - Camera

jaunty needle
#

For the V

#

I'm using screenspace camera

leaden ice
jaunty needle
#

World Space

leaden ice
#

ah yeah in world space it should also be ok I think?

spark flower
#
        TryGetComponent<Interactable>(out Interactable _int) => { _int.Interact(this); }```
is this how you write it
leaden ice
#

are you using a perspective camera?

jaunty needle
somber nacelle
jaunty needle
leaden ice
jaunty needle
spark flower
#

why you g uys hate lambda

somber nacelle
leaden ice
spark flower
#

it seems automated

leaden ice
#

this does not call for a lambda

somber nacelle
jaunty needle
#

This is what I'm using

leaden ice
jaunty needle
#

Holy shit thank you I didn't know that existed

spark flower
#
        TryGetComponent<Interactable>(out Interactable _int) => { _int.Interact(this); }```
ok can you tell me how to use lambda here
somber nacelle
#

you don't use a lambda there because it doesn't make sense to

#

again, do you even know what a lambda is?

spark flower
#

just tell me how to write it

rancid frost
#

I had just created a preset, and I want to apply it to tall the sprites in a particular folder(or game) is there a way to do this?
I have also made the preset the default preset. But, Im not sure how to apply the preset to sprites that have already been imported

leaden ice
somber nacelle
spark flower
#

how does it work then

leaden ice
#

a lambda is just a way to write a function inline without giving it a name

#

aka an "anonymous function"

somber nacelle
#

they are not a replacement for if statements

leaden ice
#

you can use a lambda anywhere you can use a delegate

#

delegates are just variables that can refer to functions rather than holding regular data

spark flower
#

so a lambda is creating a function?

rancid frost
#

yea

leaden ice
#

Yes

spark flower
#

then why not say that in the first place

leaden ice
#

e.g.

// put a function in a variable:
Action myFunction = () => Debug.Log("Hello");
// now I can call the function:
myFunction();```
somber nacelle
leaden ice
#

I used the lambda here to define the function inline

spring creek
leaden ice
#

But I could have defined the funciton normally too

dusky dune
#

i am instantiating a ui text but for some reason its not taking the position of its prefab for some reason even though I am setting it to

public class Add_Clues_To_NoteBook : MonoBehaviour
{
    [SerializeField]
    private string FileName;

    [SerializeField]
    private GameObject ui_Text_Panel;


    // Start is called before the first frame update
    void Start()
    {
        var entries = File_Handler.Read_From_JSON<Input_Entry>(FileName);

    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.X)) 
        {
            AddCluesToNoteBook();
        }
    }

    void AddCluesToNoteBook()
    {
        GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, transform.position, transform.rotation) as GameObject;
        new_UI_Text_Panel.transform.SetParent(GameObject.FindGameObjectWithTag("Left_Page_Panel").transform, false);

    }
}

why is it in this random position ?

spark flower
#

you culd have simply said that lambdas create functions

leaden ice
rancid frost
dusky dune
leaden ice
#

won't make a difference

jaunty needle
somber nacelle
#

just FYI as GameObject as part of your Instantiate line is pointless and has been so for years since the generic Instantiate method was introduced

spark flower
#

how can i fix the <T> ? its with darker color with error telling me it can be simplified

spring creek
leaden ice
leaden ice
#

delete it

#

do it like my example above

rancid frost
mystic ferry
jaunty needle
spark flower
#

ok thanks

somber nacelle
wary glen
rancid frost
dusky dune
mystic ferry
#

yes

wary glen
#

Okay cause I did that and it didn’t work

leaden ice
rancid frost
leaden ice
rancid frost
#

i read it

dusky dune
wary glen
#

@mystic ferry I’ll try to go through my administrative settings and figure it out. Thanks for the help

rancid frost
leaden ice
#

apply the preset

#

done

rancid frost
#

you can change preset of folder

mystic ferry
rancid frost
#

what if folder has sub folders etc

mystic ferry
#

you had some pipe issues earlier but the last error was a permissions error so I'd start with that

leaden ice
#

or maybe even in a folder

lucid wigeon
#

Looking at multithreading ... I mean Jobs in Unity. So if I have a large structure of say array of 1000 elements, I need to copy it over to the Job to calculate anything?

leaden ice
#

Note that you can just use the NativeArray in your non job code too

#

so it can be the main source of truth for that data, rather than having to copy it around.

sharp adder
#

I'm sure I'm having a moment, but would the prefab variables (voltage, etc) not be shown in the prefab instance?

leaden ice
#

Press Add Component and add the Power Pylon component to it

#

(and make sure you apply this change to the prefab as well)

#

Wait sorry

#

Looks like "Power Pylon" is not a component, it's a scriptable object

#

which is completely unrelated to prefabs

#

so I'm not sure what you're trying to do here

wary glen
mystic ferry
#

if I remember, the log error said you had denied the UAC prompt, it still says that even when you run as admin?

lucid wigeon
#

So let's say I have a Simplex Noise generator, I cannot store references of it in the Job. Does it mean I must copy over all noise generator code to the Job to do this? Or do I need to convert everything to static variables to make it work? PU_PeepoBigBrain

leaden ice
#

if it uses managed objects right now it will require some adjustment

sharp adder
# leaden ice so I'm not sure what you're trying to do here

Ah yes that is what I'm doing. Basically at a high level I'm trying to create a power pylon object which is instantiated by the player on a grid similar to the old SImcity games, but that (which I put as a scriptableobject in here) should have variables connected with it and functions for things next to it on the grid

#

I know I'm fumbling this

leaden ice
mystic ferry
dusky dune
#

for some reason when I try to shift the clue ui text a bit lower it ends up too low i think its becuase ui uses pixels and im using the transform

    void AddCluesToNoteBook()
    {
        Transform parent = GameObject.FindGameObjectWithTag("Left_Page_Panel").transform;
        GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, parent);

        new_UI_Text_Panel.transform.position = new Vector3
        (
            parent.transform.position.x,
            parent.transform.position.y + 0.00001f,
            parent.transform.position.z
        );   
    }

so how do I shift it down so it looks like this(image on the left) and not in middle of the panel like this(image on right)

sharp adder
#

Got it, thanks! I'll test it out now

leaden ice
mystic ferry
#

it felt like a hidden gem I stumbled upon when I first heard about them

dusky dune
#

thx will read now

sharp adder
wary glen
median current
#

I dont want to bother you all, but does anyone have experience with using authentication via Steam?

median current
#

I cant get it to work, hold on ill get the code for you.
The problem is mostly that i just dont get what i should be doing from my current situation

wind palm
median current
#

`using System.Collections;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Unity.Services;
using Unity.Services.Core;
using Unity.Services.Authentication;
using Unity.Services.Leaderboards;
using UnityEngine;
using Steamworks;

public class Login : MonoBehaviour
{
private string hex;
HAuthTicket ticketrequest;
Callback<GetAuthSessionTicketResponse_t > m_AuthTicketResponseCallback;

public async void Start(){
    await UnityServices.InitializeAsync();
    GetTicket();
    OnAuthCallback(m_AuthTicketResponseCallback);}

void GetTicket(){  
    m_AuthTicketResponseCallback = Callback<GetAuthSessionTicketResponse_t>.Create(OnAuthCallback);
    Byte[] ticket = new Byte[1024];
    uint sessionTicketSize;
    ticketrequest = SteamUser.GetAuthSessionTicket(ticket, ticket.Length, out sessionTicketSize);
    Array.Resize(ref ticket, (int)sessionTicketSize);
    hex = BitConverter.ToString(ticket).Replace("-", "");}
    
void OnAuthCallback(GetAuthSessionTicketResponse_t callback){
    AuthenticationService.Instance.SignInWithSteamAsync(hex);}
    }`
wind palm
#

It, to me, looks extremely familiar even though you're using Unity's implementation.

median current
#

I thought I did, I could have gotten overwhelmed

#

Ill check again, sorry

wind palm
median current
#

`Callback<GetTicketForWebApiResponse_t> m_AuthTicketForWebApiResponseCallback;
HAuthTicket m_AuthTicket;
string m_SessionTicket;

void SignInWithSteam()
{

m_AuthTicketForWebApiResponseCallback = Callback<GetTicketForWebApiResponse_t>.Create(OnAuthCallback);

m_AuthTicket = SteamUser.GetAuthTicketForWebApi("unityauthenticationservice");

}

void OnAuthCallback(GetTicketForWebApiResponse_t callback)
{
Token = BitConverter.ToString(callback.m_rgubTicket).Replace("-", string.Empty);
m_AuthTicketResponseCallback.Dispose();
m_AuthTicketResponseCallback = null;
Debug.Log("Steam Login success. Session Ticket: " + m_SessionTicket);
// Call Unity Authentication SDK to sign in or link with Steam.
}`

#

This is what unity tells me to do

#

i have tried a couple youtube videos as well, but there isnt much documentation about this subject

#

I forgot to add the error code, silly me:
error CS1503: Argument 1: cannot convert from 'Steamworks.Callback<Steamworks.GetAuthSessionTicketResponse_t>' to 'Steamworks.GetAuthSessionTicketResponse_t'

wind palm
#

Yeah, I cannot help you with the UnityServices side of things. I also can't really suggest move away from Unity-made stuff in the Unity discord.

#

But my question to you is, why are you trying to login? Is this a client -> server system?

#

The client has direct access to steam without keys etc

median current
#

Im making leaderboards and i need names and stuff. But im using the Unity Leaderboard and if im correct that only changes names when I use authentication methods

wind palm
shell scarab
#

I'm trying to profile something that is called a few times in a frame and this is happening instead of it just saying "called x times". Does that mean I'm not closing all my profiler samples with Profiler.EndSample()?

wind palm
#

Doing GetAuthTicketForWebApi is pointless without an authoritive server checking if it is valid.

#

Client side cannot be trusted as you can edit/mod the game

median current
wind palm
median current
#

yeah but I need it for the unity leaderboard, atleast the last time I checked

#

could be wrong, Im quiet new to services stuff

#

im gonna read the leaderboards docu again to make sure

#

yeah it needs authentication

wind palm
median current
#

Yeah, the leaderboards are all set up and can be entered anonymously because anonymous authenticating is way easier, but i need steam names hahah

wind palm
#

:/

median current
#

this is in the setup for leaderboards

#

I used this function last time and it did the job during private testing but didnt work when i let some other people play it:
UpdatePlayerNameAsync

#

Thats why i am seeking alternatives

#

Ill check it again though, and let some playtesters go at it when im ready

#

else ill be back 🫡 😎 👍

#

For me it works again, but ill need to put it into the demo now so other people can test it

rigid island
dusky dune
#

I am trying to access all the instantiated ui text in my game and make each text equal to something different.

I know I will use a for loop to loop through each ui text panel but dont know how to access each element?


        var entries = File_Handler.Read_From_JSON<Input_Entry>(FileName);

        Transform parent = GameObject.FindGameObjectWithTag("Left_Page_Panel").transform;
        GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, parent);

        for (int x = 0;  x< entries.Count; x++)
        {

            ui_Text_Panel[x];

        }
median current
#

Do you mean like

"ui_Text_Panel[x].text"

?

dusky dune
#

because the text panel has a description of a clue so each text panel is going to have a unique clue description

hard viper
#

if I update if my player is grounded using OnCollisionStay/Enter/etc, then use that information in fixed update, then my information is by its nature 1 frame late, right?

wind palm
#

FPS can be crazy like 1000 times per second, where as physics is ~50 by default

#

Update is tied to FPS

hard viper
#

I mean script execution order

rigid island
#

not sure what ur doing there tho @dusky dune

wind palm
#

Then it'll run in the same frame

hard viper
#

oncollision gets called after fixed update

#

so if I set isGrounded in OnCollisionEnter, then the information in fixedupdate is old, right?

somber nacelle
dusky dune
# rigid island not sure what ur doing there tho <@495261393721753621>

so I need to instantiate ui text in the game ive done that but I now need to fill each text box with a unique description I have the description in a JSON file and I need to read each description one text box and then move on the other other text box and read the description in. Make sense?

hard viper
#

I see. So is there a way for me to generate collision data to use that same frame?

dusky dune
somber nacelle
somber nacelle
dusky dune
#
public class Add_Clues_To_NoteBook : MonoBehaviour
{
    [SerializeField]
    private string FileName;

    [SerializeField]
    private GameObject ui_Text_Panel;
    [SerializeField]
    float ShiftClueText;

    // Start is called before the first frame update
    void Start()
    {

        var entries = File_Handler.Read_From_JSON<Input_Entry>(FileName);

    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.X)) 
        {
            AddCluesToNoteBook();
        }
    }

    void AddCluesToNoteBook()
    {

        var entries = File_Handler.Read_From_JSON<Input_Entry>(FileName);

        Transform parent = GameObject.FindGameObjectWithTag("Left_Page_Panel").transform;
        GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, parent);


        for (int x = 0;  x< entries.Count; x++)
        {
            TMP_Text theText = new_UI_Text_Panel.transform.GetComponent<TMP_Text>();

            //Sets the text.
            theText.text = entries[x];
           

        }


        
    }
}

is what ive done so far

rigid island
#

this x< fucking spacing is irking me

somber nacelle
dusky dune
somber nacelle
#

clearly not. what field on your Input_Entry class has the string you want

dusky dune
somber nacelle
#

great! so you need to assign that string to the text property of your TMP_Text object

#

also keep in mind that you'll only see the last entry in the list with how your current code is set up because you instantiate a single object and just reassign its text property every iteration of your loop

dusky dune
somber nacelle
#

what?

dusky dune
#

soz I mis typed

somber nacelle
#

that still doesn't make any sense in the context of the code. you've already deserialized your json at this point. you've got your List<Input_Entry> that you are iterating over. access the Clue_Description field/property inside that loop to assign to the text object

dusky dune
#

oh right now I understand better thank u

hard viper
#

follow-up question: If I use GetContacts, would my information still be a frame late?

#

or would it be from that current frame

dusky dune
#

I am getting an index out of range error even though the for loop is <= why is this couldnt find much on google

    void AddCluesToNoteBook()
    {
        var entries = File_Handler.Read_From_JSON<Input_Entry>(FileName);

        Transform parent = GameObject.FindGameObjectWithTag("Left_Page_Panel").transform;
        GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, parent);
        TMP_Text theText = new_UI_Text_Panel.transform.GetComponent<TMP_Text>();

        for (int x = 0; x <= entries.Count; x++)
        {
            Debug.Log(entries.Count);

            //Sets the text.
            theText.text = entries[x].ToString();

        }

    }

as you can see the count is 4 but the index is 5

#

why is it going one over ?

somber nacelle
#

because when it reaches entries.Count it is still allowed to proceed depsite .Count being 1 more than the final index

#

you want it to be less than entries.Count, not less than or equal to

#

entries[x].ToString() this is also wrong

#

and you are still assigning the text of just a single object so only the last entry will be visible

dusky dune
somber nacelle
#

yes and i already told you how to fix that. you clearly ignored it

rigid island
#

if u want multiple ones

dusky dune
dusky dune
rigid island
#

put them in a list then

dusky dune
# somber nacelle `entries[x].ToString()` this is also wrong

I mean it works now as intended

    void AddCluesToNoteBook()
    {
        var entries = File_Handler.Read_From_JSON<Input_Entry>(FileName);

        for (int x = 0; x < entries.Count; x++)
        {
            Transform parent = GameObject.FindGameObjectWithTag("Left_Page_Panel").transform;
            GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, parent);
            TMP_Text theText = new_UI_Text_Panel.transform.GetComponent<TMP_Text>();

            Debug.Log(entries.Count);
            Debug.Log(x);
            //Sets the text.
            theText.text = entries[x].ToString();

        }

    }

does using the toString really harm it?

somber nacelle
#

it very likely doesn't do what you think it is

somber nacelle
#

literally all you needed to do was access the public Clue_Description field on the object rather than call ToString on it

heady iris
dusky dune
# somber nacelle literally all you needed to do was access the public `Clue_Description` field on...

so this

    void AddCluesToNoteBook()
    {
        var entries = File_Handler.Read_From_JSON<Input_Entry>(FileName);

        for (int x = 0; x < entries.Count; x++)
        {
            Transform parent = GameObject.FindGameObjectWithTag("Left_Page_Panel").transform;
            GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, parent);
            TMP_Text theText = new_UI_Text_Panel.transform.GetComponent<TMP_Text>();

            Debug.Log(entries.Count);
            Debug.Log(x);
            //Sets the text.
            theText.text = Input_Entry.Clue_Description[x];

        }

    }
rigid island
somber nacelle
#

bro what the fuck

#

do you not know how to use c#? because if not, you should really consider doing some basic courses instead of just guessing

dusky dune
#

I do ive used it in the past

somber nacelle
#

then what about Input_Entry.Clue_Description[x] do you think is correct?

dusky dune
#

well I need to get the x index of input_Entry no?

somber nacelle
#

that sentence makes very little sense

#

x is a variable used to index your entries list

#

it has nothing at all to do with the Input_Entry class other than the fact that entries is a list of Input_Entry

heady iris
#

if you can't see the problem here, you have a severe misunderstanding of how variables work, in general

#

theText.text = entries[x].ToString();

#

explain to me what this line does

dusky dune
#

that was my reasoning

heady iris
#

close, but your ordering is weird

#

It gets the xth element of entries and calls ToString on that

#

then it sets the text field on theText equal to whatever the result is

#

now

#

theText.text = Input_Entry.Clue_Description[x];

#

where did entries go?

rigid island
#

man those underscores makes evertyhing a chore to read..

heady iris
#

they do, yes

somber nacelle
#

i feel like this person doesn't even have a configured IDE considering the monstrosity of that line

heady iris
#

that should be emitting a large pile of errors, yes

wind palm
somber nacelle
#

although i guess technically it would be valid if Clue_Description was made static for whatever reason. since you can index a string. still wouldn't do anything close to what they want to do though

rigid island
#

it should be in beginner lol

heady iris
#

oh yeah, that's most of the way to compiling

wind palm
somber nacelle
rigid island
dusky dune
somber nacelle
#

no, it's a List<Input_Entry>

#

entries[x] would be an Input_Entry

heady iris
#

why did you get rid of entries?

#

i am trying to grasp how you're making this error so you can fix that misunderstanding

dusky dune
heady iris
#

where are you "loading the list in"?

somber nacelle
heady iris
#

well, let me get ahead of you there and say that this is...not a thing

#

you have a severe misunderstanding of how this works

dusky dune
heady iris
#
for (int i = 0; i < 1000; ++i) {
  Debug.Log(i);
}
#

This just counts from 0 to 1000 and logs the numbers

dusky dune
#

yes I know that

heady iris
#
for (int i = 0; i < entries.Count; ++i) {
  Debug.Log(i);
}
#

Okay, so what does this do?

dusky dune
somber nacelle
heady iris
heady iris
dusky dune
heady iris
#
int num = entries.Count;

for (int i = 0; i < num; ++i) {
  Debug.Log(i);
}
#

entries appears nowhere in this for loop at all.

dusky dune
#

right but you reference it with num?

heady iris
#

num is an integer

#

It is a dumb number that does nothing interesting.

dusky dune
#

but wouldnt the number of num be equivalent of the entries length?

heady iris
#

Yes.

heady iris
#

It would not "load the array elements" through some ill-defined mechanism

#

It just counts from 0 to 1000 and stops

#

That's it.

#

Now.

dusky dune
#

so far im with u

heady iris
#
for (int i = 0; i < entries.Count; ++i) {
  Debug.Log(entries[i]);
}
#

what does this log?

hard viper
#

Do collider contacts only get updated in the internal physics update? I’m having trouble finding info

somber nacelle
#

yes

heady iris
#

what does it give you?

rigid island
dusky dune
heady iris
#

I would say zeroth, but it's certainly the "first" one, yeah

#

thanks indexing

#

So, entries[0] is not an index

somber nacelle
heady iris
#

It's an element of the list

dusky dune
dusky dune
heady iris
#

Right.

dusky dune
#

by going through each index of th elist

heady iris
#

theText.text = Input_Entry.Clue_Description[x];

#

This is trying to use something named Input_Entry

#

It's trying to get a member named Clue_Description from it

#

Then it's trying to get the xth thing from Clue_Description

#

notice how entries is nowhere to be found

#

so we ain't getting elements from a list, for sure

dusky dune
#

right I get u now I think what confusing me is because the variable entries has the list Input_entry and the input entry class has the clue_description

heady iris
#

entries is a List<Input_Entry>

#

Therefore, entries[x] is an Input_Entry

#

writing Input_Entry.Clue_Description is wrong. You need a specific Input_Entry to get the clue description from.

plain dock
#

hello , i am tring to create a serilizable class that has a setup window

[Serializable]
public class WKArgsFloating<T, U> : WKArgsBase where T : WKArgsWindow<U> where U : WKArgsBase
{
    public void ShowWindow()
    {
        T window = ScriptableObject.CreateInstance<T>();
        window.args = this as U;
        window.Init();
    }
}
public abstract class WKArgsWindow<T> : EditorWindow where T : WKArgsBase
{
    public T args;
    public static Vector2 size;
    public abstract void Init();
    private void LostFocus() => Close();
}

i got this so far, is there a simple way to do that?

heady iris
#

you're asking the concept of an Input_Entry to give you a Clue_Description

#

entries is a List<Input_Entry>, so entries[x] is an Input_Entry, so entries[x].Clue_Description is a string

#

(because, I presume, your definition for Input_Entry includes something like public string Clue_Description;)

dusky dune
#

thx for dumbing it down

heady iris
#

I have a List<Foo>, so I can get a Foo by indexing it

#

Foo has a string field, so I can get a string by accessing that field

shell scarab
#

For Cancelation Tokens do I just need to check if IsCancellationRequested is true whenever there is a loop? I'm thinking I'll supply it and set it to true when exiting play mode so the task stops. I don't want to use the Job system because It won't let me use managed objects which is a big inconvinience for me for this specific task...

lethal mantle
#

Hey I'll this isn't made for asking for scripts but does anyone have time to teach me how to make a 2d character move

leaden ice
wind palm
lethal mantle
#

Left right and jump

wind palm
leaden ice
#

you might be surprised to hear that your description is nowhere near a complete description of a character controller

leaden solstice
lethal mantle
#

I just started

shell scarab
leaden solstice
dense stag
#

I am having trouble fetching my assets, yes I am logged in, yes I logged in and out.

spring creek
rigid island
#

at least in ur region it seems

dense stag
#

Ok whewf, I am happy its not a me problem

wind palm
#

Yeah, error 400 is a bad request

#

So it could be a whole host of things.

dense stag
#

I asked around for where to post this and they recommended here @glacial cliff ...

dense stag
#

literally you

#

"code channels"

rigid island
#

you said Bugs

leaden ice
rigid island
#

i assumed coding bugs sorry

wind palm
rigid island
#

thats not a coding bug lol

wind palm
dense stag
#

I am not here to argue...

#

lmfao

#

Thanks for the help guys

leaden ice
rigid island
#

what region are u in? its working in US

dense stag
#

New Zealand

wind palm
dense stag
#

Australia

#

Servers probably

rigid island
#

seems like Oceania issue

#

lots of AU and NZ ppl

glacial cliff
wind palm
shell scarab
# leaden solstice Generally if you don’t need cleanup you can just return or throw when it is canc...

yea I don't think I'll need cleanup. So basically just something like this pseudocode?

TaskLoop() {
  while(working) {
    if(token.IsCancellationRequested)
      return;

    // do work
  }
}
static class CancelTasksOnQuit {
  private static CancellationTokenSource onQuitTokenSource;
  public static CancellationToken CancelToken => onQuitTokenSource.Token;
  
  static CancelTasksOnQuit {
    (application quit event) += OnQuit;
#if editor (player stop event) += OnQuit;
  }

  private OnQuit() {
    CancellationTokenSource.Cancel();
  }
}
StartTask() {
  Task.Run(() => new TaskClass(CancelTasksOnQuit.CancelToken).TaskLoop());
}
rigid island
#

thats on me for redirecting in the wrong channel thinking Bugs meant code UnityChanLOL

glacial cliff
wind palm
quartz folio
glacial cliff
#

Not complaining or anything, just thought it was funny that the post became relevant. Also your right, there is no #unity-bugs.. bit odd?

wind palm
quartz folio
#

Read the channel descriptions

#

It's not difficult

wind palm
glacial cliff
#

"Non-programming Unity topics & questions not covered by specific channels."
"I started a new project and got 300 errors, here is detailed information that I'm just going to dump in the general discussion area"

dense stag
#

really...

wind palm
quartz folio
#

Make a thread if you are worried about it

spring creek
wind palm
#

Yeah, I just wouldn't argue about it. You're not going to win here.

dense stag
#

Didn't know people could get this triggered about a simple question in the wrong channel

heady iris
swift falcon
#

so, seemingly randomly, my scenes shadows started looking super dark and I have no clue what I did or how to fix it. Any suggestions? I am using the Built In Render Pipeline

swift falcon
#

ok, Ill check it out, thanks

#

It was a lightmap issue. thanks so much!

dusky dune
charred swift
swift falcon
charred swift
swift falcon
charred swift
worldly hull
#

i can tell theres not much texture used lol

twilit echo
#

with scriptableobjects, i'm trying to reference a gameobject prefab (from resources folder), but when i instantiate the scriptableobject, the gameobject variable is empty
it's still set in the scriptableobject asset, just not the instantiated one
anyone know what's going on?

shell scarab
#

I can't seem to find the answer online... my suspicion is no.

Can I invoke an event/delegate from a worker thread on the main thread? i.e. if I pass a System.Action into a task, then have the task call action.Invoke(), it will invoke it on the task thread, right?

If this indeed doesn't work, is there some way I can notify the main thread that the task is finished?

leaden solstice
shell scarab
leaden solstice
#

Threading is not easy topic

dusk apex
#

Seems completely isolated or rather decoupled from Unity, try the c# server.

urban orbit
#

If I have two virtual cameras and I want to convert the player's mouse screen pos to the world pos of the secondary vcam at the time, how can I accomplish this?

#

because a virtual camera doesn't have the method of ScreenToWorldPoint(). So I'm only stuck with using ScreenToWorldPos for the main camera which ruins my game functionality.

shell scarab
urban orbit
#

so I want the secondary camera to be for the game functionality and the main one to display the game but with another angle

wind palm
swift falcon
earnest gyro
#

Desperate Fight with a NRE

modern creek
#

Any tips on finding the offending game object for renamed/moved scripts? I did some refactoring and this error message is unhelpful (even in 2022.3.7f1). When will this be more useful, unity? >:|

#

double clicking it doesn't bring me to the GO, and i don't see a stack trace

wind palm
modern creek
#

Hm, so recursively crawl everything in the scene looking for valid components (ie, counting them, iterating "known" ones, then spitting out the name/path of the GO when it misses). Nice trick.. Not sure it'll work for my use case though since I'm seeing that error on awakes/scene transitions.. but I might be able to adapt this a bit.

modern creek
#

I probably ought to have saved my project before clicking something that's going to recurse through the entire hierarchy 😛

#

Works great though. Thanks!

low horizon
#

im making a list of every upgrade (scriptable object) in my game

#

should this list be static or non-static?

#

would a static list cost more memory

lean sail
low horizon
#

like this

#

i don't need it static but i dont want to load it again every time i switch scenes

lean sail
#

I dont see how switching scenes is related, you could place it inside DDOL as a way to keep it across scenes

mossy snow
#

probably would be better to make it a SO in its own right and have objects that need it take the SO as a serialized field. Doesn't make sense to have a list of upgrades exist in the scene, and imo your code snippet is very smelly

low horizon
#

yeah static solution was bad

#

ddol would be nice but so would be best here ig

low horizon
#

thanks for the help by the way

mossy snow
#

public, static, mutable list. Init flag. Has an awake, so now you can have execution order issues if anything else accesses that list in their own awake

#

the comment suggests it scans from resources folder instead of just having those items assigned

low horizon
#

thanks for clarifying

#

im now sure this was a bad idea

#

ill use scriptable object for that

gloomy anchor
#

Hi everyone, I need help with an issue. I am making a Stardew Valley - type of game and I am working on an inventory system. Now, I have never build such a system, but I decided to model the inventory by an array of InventoryItems. I create an array on Start, but when I try to read through it, I get a NullReference error. Then, when highlighting the player GameObject in the inspctor (which holds the InventoryManager script) and I try reading from the array, the error goes away and it works perfectly fine. To me, it looks like the array is only created when selecting the script in the inspector. I don't want to link all the code here, If you know how to help me and need some of the code just ask for it please. Thanks

lean sail
#

a null ref error is the same thing every time. its just a matter of debugging whats null and why

gloomy anchor
#

this is the error btw

lean sail
#

did you change anything from the script before sending? 120 is just an empty line, so i assume its 121

gloomy anchor
#

just removed some comments

#

the error is on this line: if (list[i].item == null)

lean sail
#

you can step through with the debugger to see what part is specifically null

#

I assume its the list[i] part because i dont see where you initialize those classes inside the list

gloomy anchor
#

Item is a ScriptableObect

#

I use them to model items

lean sail
#

i edited the message, i meant list[i]

gloomy anchor
#

oh

#

this are the logs if you add a debug.log(i) just above the error line

#

I start the game with nothing highlighted, and after the error I highlight the player gameobject from the hierarchy

#

and it just works

lean sail
#

are you doing this all in 1 consecutive run? you should have error pause on because nothing should really run after this error

#

this also doesnt really change that list[i] can be empty considering some of your code does
Inventory = new InventoryItem[slotsCount];
then immediately searches on it

gloomy anchor
#

I don't have error pause on

#

I didn't even know it existed unitil now

#

so how should I create the array?

lean sail
#

the array is fine, but the items inside the array havent been created

gloomy anchor
#

should it be like a loop and use Inventory[i].item = new InventoryItem() ? or something like this ?

lean sail
#

you should debug to see what part is specifically null, maybe itll be more clear then

#

like use the debugger or just check list, then list[i] and list[i].item

dusk apex
#

Should you be creating new instances or referencing already existing instances.

gloomy anchor
#

i'll try and come back

#

I understand now

#

so the array is created and assigned, but each individual object in the array is null, so I can't reference any array[i].item

#

I added Debug.Log(list[i] == null and it returned true

#

but how does highlighting something in the editor changed that ?

lean sail
#

it shouldnt really, I just assume you have the function calling from different origins but its hard to really say without more knowledge.
Regardless, you just have to fill in the array with valid entries of InventoryItem

gloomy anchor
#

I changed it to this: ```Inventory = new InventoryItem[slotsCount];

    for (int i = 0; i < slotsCount; i++)
    {
        Inventory[i] = new InventoryItem(null, 0);
    }```
#

and it worked

#

but I will try and find out if there is a more performant way of doing this

lean sail
#

🤷‍♂️ that is your way of doing it, you're gonna have to new them all up anyways

#

actually what you could do is just check if item[i] is null, meaning no entry was ever put in that slot and then create it if its null. But this really just delays the inevitable of newing up an InventoryItem

gloomy anchor
#

this runs in start, so I should never be null in Update

#

but I assume doing it once this way isn't that bad

lean sail
#

Id put that new Inventory thing in Awake but yea itd be fine still.

gloomy anchor
#

I had it in awake but changed it for some reason

#

but I put it back now

lean sail
#

Unless you're inventory is literally 1 million size, you'll not notice any lag. And at that point, memory is more an issue instead of performance

gloomy anchor
#

exactly

#

ok, thanks a lot

crystal birch
#

you guys got any methods to make good random map generation

#

i was thinking of having premade rooms and just using spawnpoints like blackthronpods video just changing it up a bit

crystal birch
#

that gibs an idea

#

thank u man with lucious hair

upper patrol
#

In my android build when I take a screenshot of my screen I get the problem that the rendertexture that I use for my map gets black. When I dont take the screenshot the rendertexture of the map works. fine.

daring cove
#

Hey, how can I fix this?

I'm steering a missile, but it is oversteering because it's applying too much correction.
Limiting correction by 50% or limiting it over distance to the steeringPoint doesn't fix the oversteering. It's less, but the oversteering still accumulates over time and also the turn rate is affected.

The angular velocity of the missile is linearly interpolated.

// direction to the current steeringPoint
Vector3 direction = guidanceSystem.missileTransform.position - steeringPoint;

// calculating angles to steeringPoint.            
float verticalAngle = Vector3.Angle(direction, guidanceSystem.missileTransform.up)-90;
float horizontalAngle = Vector3.Angle(direction, guidanceSystem.missileTransform.right)-90;

// This keeps error in range of turn rate
horizontalAngle = Mathf.Clamp(horizontalAngle, -guidanceSystem.yawSpeed, guidanceSystem.yawSpeed);
verticalAngle = Mathf.Clamp(verticalAngle, -guidanceSystem.pitchSpeed, guidanceSystem.pitchSpeed);

// setting how much correction to apply in each direction
float verticalError = verticalAngle / guidanceSystem.pitchSpeed;
float horizontalError = horizontalAngle / guidanceSystem.yawSpeed;

Vector3 correction = new Vector3(verticalError, horizontalError, 0);
guidanceSystem.SetGuidance(correction)

In the image the green line is the route for the missile and the pink line is for where the missile travelled.
You can see how the oversteering accumulates over time

autumn sail
#

Im making a game and its working fine when i play from the editor but after dying and reloading the scene it does something different (not work), theres no errors and some things work but a lot doesn't, what are the differences between the initial play and scene load?

wintry crescent
autumn sail
#

dont think so although my events are which might be why

#

can you make non-static events?

wintry crescent
#

It very likely is the problem, happened to me many times

autumn sail
#

alright, thanks ill try that

lucid wigeon
#

If I have call structure like:
Update() -> A -> B -> C -> D and I want to try to turn D to use threads and UniTask with async / await...
does it mean I also have to change A B C to async as well?

#

Can Update even by async?

#

I have a headache even thinking about it... I've moved my FastNoise generation from one place to to during terrain mesh generation so that I don't have to store it in memory and now the game is all jittery and I'm trying to put it in background somehow because all FastNoise calls take like 100ms and fps drops during that time

tired elk
lucid wigeon
#

But maybe it was a mistake to move it. Before I stored all cube values in 3D mesh. But I figured I don't need to store the noise generated values if I can generate them anyway on the fly. But it turns it's slow to generate them on the fly aPES_Think

#

This FastNoise script makes some fractal calls and crazy math loops which I don't understand which take some time

tired elk
#

Do you need it to be done more than once ?

lucid wigeon
tired elk
#

OK

wanton wasp
#

Sorry for the off topic, but is 150 TB read/write a lot for a 256 GB ssd?
I'm asking, because my pc won't boot for an hour or so due to disk check.

proven path
#

Is there any way to have an event which fires whenever a pointer is pressed anywhere?

proven path
#

Yeah, but also a touch for instance.

wanton wasp
#

Are you using a new input system or an old one?

proven path
#

the new one.

tender coral
#

@proven path

proven path
#

I see, I would want soemthing like the second one, but not bound to an object like in the example.

tender coral
#

do u need object?

#

u want tourch turn off and on on button click?

leaden ice
#

Unverified AI responses are banned in this discord BTW

proven path
#

Thanks you guys!

tender coral
#
{
   var mousePosition = Input.mousePosition;
   var ray = Camera.main.ScreenPointToRay(mousePosition);
   RaycastHit hit;

   if (Physics.Raycast(ray, out hit))
   {
        // Check if that is your object, but then you will need a collider.
        this is much better
   }
}```
#

i am using this kind of logic everywhere. it is more simple than distance of 1000 of canvas @proven path

#

!eventSystem.IsPointerOverGameObject() this part is just checking if mouse is over gameobject not a ui elemet

leaden ice
#

I disagree that this is more simple at all

proven path
lucid wigeon
#

If I use UniTask do I need to use UniTask.Create() or can I just write await SomeAsyncFunction() ? if it is public UniTask async SomeAsyncFunction(){}

#

I'm having some strangest bug where my code won't even run or throw any errors anymore and I don't see what's going on

wanton wasp
scarlet viper
#

if i wanted to disable the gravity and add my own, what the code would be like?

leaden ice
scarlet viper
#

i now understand why my vehicle kept sliding from mountains/slopes/etc. it was gravity

#

kinda obvious but somehow it escaped me

daring cove
#

Hey,

How to get an angle in a 180deg range to a object?

This only returns an angle in 90deg range, and also works in reverse?

Vector3 direction = target.position - antenna.position;
float verticalAngle = Vector3.Angle(direction, antenna.up)-90;
float horizontalAngle = Vector3.Angle(direction, antenna.right)-90;
heady iris
#

You may want SignedAngle

#

oh, I see

#

I thought you were trying to get angles in the range [-180, 180]

#

I did something really similar a few days ago. Getting the pitch and yaw components takes a little more work.

daring cove
#

How would I get it to work like this:
forwards = 90
left = -180
back = -90
right = 180

#

In both vertical and horizontal

heady iris
#

would a yaw value (rotation around the up axis) and a pitch value (rotation up or down from horizontal) work?

#
            Vector3 flattened = Vector3.ProjectOnPlane(entity.transform.forward, Vector3.up);
            yaw = Vector3.SignedAngle(Vector3.forward, flattened, Vector3.up);

            Vector3 rotated = Quaternion.AngleAxis(-yaw, Vector3.up) * entity.transform.forward;
            pitch = Vector3.SignedAngle(Vector3.forward, rotated, Vector3.right);

Here's how I did that in my game.

#

It first squashes the direction into the XZ plane (removing the vertical part) and computes a signed angle

#

Then it undoes that rotation to give you a vector that points up or down, straight ahead

#

And then it computes another angle.

daring cove
#

Can this be used to calculate an angle to an object?
Like Line Of Sight

heady iris
#

No, I did this because I needed to know the yaw and pitch to set up the player input correctly

#

(so that taking control of an entity doesn't make it spin to 0 yaw and 0 pitch)

#

Are you trying to calculate line of sight for an antenna on a planet's surface?

#

if you want LOS, you usually just use a raycast

daring cove
#

I'm precomputing what targets I need to raycast

#

I'll exclude targets that are out the radar antenna's range and fov

#

then raycast to query wheater the target is blocked by terrain

#

                Vector3 direction = target.position - antenna.position;
                float range = Vector3.Distance(target.position, antenna.position);
                
                float verticalAngle = Vector3.Angle(direction, antenna.up)-90;
                float horizontalAngle = Vector3.Angle(direction, antenna.right)-90;

                bool outOfCone =
                    verticalAngle < maxVerticalAngles.x ||
                    verticalAngle > maxVerticalAngles.y ||
                    horizontalAngle < maxHorizontalAngles.x ||
                    horizontalAngle > maxHorizontalAngles.y ||
                    range > maxRange;
#

Targets that are outOfCone are not raycast

heady iris
#

Do you need separate horizontal and vertical components?

daring cove
#

yes

heady iris
#

okay, so you can just do one Vector3.Angle query

#

hm, so you need to separately figure out the dispersion on two different axes

heady iris
#

You need to use Vector3.ProjectOnPlane to throw out the vertical and horizontal parts of the direction vector, then do the Vector3.Angle calculation normally

#

Vector3.ProjectOnPlane(direction, antenna.right) would give you just the up-down part

#

Vector3.ProjectOnPlane(direction, antenna.up) would give you just the left-right part

#

ProjectOnPlane flattens the vector onto a plane with the specified normal vector

#

Then, compute Vector3.Angle(flattenedDir, antenna.forward) to get an angle.

heady iris
#

if the normal vector is +Y, the resulting vector will only have X and Z components

daring cove
#

Okay thats new to me. Give me sec I'll try to implement this

heady iris
#

It's super useful.

#

You might do something like this...

#
Vector3 something = whatever;
something.y = 0;
#

ProjectOnPlane can do the same thing, but in any axis

#

The opposite is Project. It returns only the part that aligns with the second vector.

#

(project-on-plane just subtracts the result of Project)

swift falcon
#

How can i show Non-Serializable struct (UnityEngine.ResourceManagement.ResourceProviders).**InstantiationParameters **in inspector? I searched and also tried PropertyDrawer but didnt work.
I have no idea why they did not marked this one as Serializable...

swift falcon
heady iris
#

I don't think a property drawer even comes into play if it's on something that isn't serializable

swift falcon
#

Yep

heady iris
#

serialized properties and all that

#

The first thing that comes to mind is making your own version of that struct that is serializable

#

and just copying the values into it

swift falcon
#

Yep obviously

#

So no way?

heady iris
#

a custom editor could probably do it

swift falcon
#

Oh

#

Rİght

heady iris
#

but custom editors are more of a nuisance

dusk apex
#

There aren't a lot of members

swift falcon
#

I can deal with it. I will try the Custom Editor

swift falcon
hard viper
#

i don’t understand the issue

#

there is a struct that is defined and non-serializable? or you defined a struct and want it to be non-serializable?

latent oak
#

Hey all, i need some advice, whats the best way to implement the syncing of data that isnt a Mono/NetworkBehavious class. Or do I do it in the class that is a network behaviour.In my case I have an Inventory system where the "physical" inventory classes are not monobehaviours. however the inventory is attached in a monobehavious class. So do I just call a serverRpc to update that inventory? within the networkbehaviour containg the inventory

void SyncInventoryServerRpc(Inventory inv){
  inventory = inv
}
upper patrol
#

Anyone experience with creating screenshots for android? It destroys the renderTexture connection of my map gob?

stuck robin
#

How do i use NavMesh.CalculatePath(...)? the func keeps returning false for my maze despite their sometimes being a path between the two points.

#

(I'm trying to build a spawn checker)

stuck robin
#

spawn points and exit points are simply a transform attached to a tile game object that is then passed into a wave function collapse generator. the script is attached to the parent spawn tile and calls at Start()

#

every tile is returning false tho

rigid island
stuck robin
#

let me check

rigid island
#

if its false, somehow its not a complete path

stuck robin
#

hmm the path status says PathInvalid

#

hmm

rigid island
#

oh alr. well time to make it valid then

stuck robin
#

hmmm maybe it has to do with generation of the nav mesh grid

#

basically the tiles are assembled in the awake method

#

the nav mesh is built in the start method which is called second

rigid island
#

so you call calculatepath before the nav is baked ?

stuck robin
#

maybe

#

im guessing anywya

rigid island
#

dont guess, test

#

lol

#

put the baking in Awake

stuck robin
#

that or i specifically write the code that calls the spawn point checks after the nav mesh build

rigid island
#

true

#

i try not to rely on order of unity events

stuck robin
#

okay yeah, putting the generation code in the awake method allowed the paths to execute as true.

#

same

#

The WF collapse generator also runs in the awake method and i was separating those concerns but they seem to both run fine in the awake method

#

but if i have to i guess i will use unitys order of events

rigid island
stuck robin
#

hmm ive seen a more generalized version

orchid bane
#

How do I find out whether a point is to the right or to the left of a direction?

harsh bobcat
#

Im pretty sure default(customClass) is null, is it the same for default(Vec3Int)?

harsh bobcat
orchid bane
#

It's 2d

harsh bobcat
#

so you have a player position and a forward and you want to see if a point is left or right

orchid bane
#

Cross product*

harsh bobcat
#

you can use dot product

#

from stackoverflow:

float dot = a.x*-b.y + a.y*b.x;
if(dot > 0)
    console.log("b on the right of a")
else if(dot < 0)
    console.log("b on the left of a")
else
    console.log("b parallel/antiparallel to a")
orchid bane
#

Are you sure it's dot product and not cross?

#

Or can both be used

#

Because I saw cross on the Internet

thick terrace
harsh bobcat
#

dot product is more in front of or behind, but if you use a vector 90 degrees form the one you want it works

marble halo
#

For some reason it won't let me set the position where the projectile spawns with the remote bomb ability

#

notice how spawn point says "Type Mismatch"

glass berry
#

anyone know if it is possible to have c# create a wrapper for python scripts to be ran in unity. I wanna use this: https://github.com/Osmodium/PathfinderTextToSpeechMod
Then instead of using the windows commands (natural narrator is not supported in their library). I would use the google chrome.tts with edge or chrome to pass in the text to be read. It doesn't need chrome to be installed on windows, just on mac. But it should be able to cancel the audio and receive everything from a c# script

GitHub

A mod that introduces text to speech in various parts of the game. - GitHub - Osmodium/PathfinderTextToSpeechMod: A mod that introduces text to speech in various parts of the game.

#

In short, I am looking for existing wrapper libraries that could accomplish this

wanton wasp
marble halo
#

damn, how am I gonna have projectile abilities then

#

im trying to make abilities flexable

rocky helm
glass berry
#

also I know you can call chrome.tts in a c# script since its through the api. I am just thinking of using another github project to make it easier

marble halo
#

yeah which requires a transform

mystic ferry
#

you have to make the scriptable object a field inside a monobehaviour class

#

scriptable objects are basically just instances of data

wanton wasp
# marble halo im trying to make abilities flexable

Just make a POCO c# class with a mobo wrapper.

[Serialized]
class Ability 
{
    string Name;
    string Description;
    ...

    public Ability(string name, string description, ...)
    {
      Name = name;
      Description = description;
    }
}

class AbilityWrapper : MonoBehaviour
{
    [SerializedField] Ability ability;

    void OnAbilityUsed()
    {
      ability.DoSomeStuff();
    }
}
marble halo
#

POCO?