#archived-code-general

1 messages Β· Page 77 of 1

thin aurora
#

Probably because KeyValuePair can not be serialized

tired drift
#

hm

#

guess i'll have to transform it manually

thin aurora
#

Or make a custom editor for it

#

Or for a dictionary in general

tired drift
#

will do later on, just didn't want the hassle rn cuz i wanted to check it out really quick

#

but ty blush_cat

brave lintel
#

Hello everyone, I have a quick question. In my scene, I have a public class called GameAdmin, which stores critical game data and variables. When I instantiate different players, I have to access the GameAdmin by using FindGameObject or FindObjectWithTag commands. It is getting heavier while having more objects trying to get data from GameAdmin. Is there anyway to achieve this by using something else like static methods?

thin aurora
#

Something like that

#

Then you can access it using GameAdmin.Instance

#

Note this only works if you are sure to only have a single GameAdmin

brave lintel
thin aurora
#

If you want to really make it look good, you should implement a sort of dependency collection where you get it from, instead of having each manager have their own Instance. Then you grab it from that collection, or allow it to make a new one if it does not exist. This is how Dependency Injection works in C#

#

But as a quick fix, having it implemented in the behaviour itself works

brave lintel
#

I have many dependencies and cached objects, variables in the GameAdmin. If I do it static, I would not be able to use its instance in the scene?

thin aurora
#

Yes

#

Just know that if your scene unloads, the singleton object no longer exists, but the reference does. So be careful with it

#

You could add an OnDestroy method and set Instance to null, but this gives edge cases where it might not exist so honestly you should just make it persist between scenes and clean it up properly when you need it to.

brave lintel
#

Thank you, I will check the link and try to implement

olive shore
#

anyone know how to fix this?

[Collab] Collab service is deprecated and has been replaced with PlasticSCM

somber nacelle
#

stop using collab and use unity Version Control (formerly called PlasticSCM)

#

or switch to git. either way, it's been more than a year since collab was shutdown

olive shore
#

my version control is 2.0.3 tho

olive shore
#

fixed it, just turned off collab πŸ€·β€β™‚οΈ

urban marsh
#

Hello everyone !
I am currently working on a part of the UI for my game : displaying skill trees.
As these are randomly generated, I am currently creating a script that will draw the skill tree for the user when needed.
I have already done the part where I decide which skill goes where (pixel-wise), and I have created a list of "skills" (using an interface so I can easily grab their icons and names and stuff), and a list of coordinates (Vector2) where I want them in my tree.
now, on to the real "drawing" part :
I have my "container" where I want to create my prefabs.
should I just instantiate them inside it (with the container as parent transform) like I would to with units/enemies/projectiles in the game world, or is there a UI-specific way to do it ?

latent latch
#

You wouldnt instantiate the skill as a gameobject if that's what you're asking. Your container should have a script that contains a reference to the data of the skill, and information to display such as the sprite which you can put on the skill tree.

urban marsh
#

what do you mean ?

#

I should have "already created" empty skills in the container, ready to be filled and moved when changing the tree to display a new skill tree ?

latent latch
#

Your container, the visible part is displayed as a rect, right? You'd send a raycast or however you want to select to that gameobject which will contain some script such as a 'Slot'. This slot should contain the data (to instantiate into the scene) of your skill which you can then retrieve it from.

urban marsh
#

I didn't understand a thing you said :/

latent latch
#

Using the UI and canvas is usually the way to handle such things if you're interested in that method.

#

But since it looks like you're doing 2D I'm pretty sure you can handle it in a similar way.

thick bough
#

They're asking how to do it in UI though

#

Yes you would just instantiate an object like you do regular transforms @urban marsh, however an additional layer of complexity with UI is how RectTransformss are anchored to the screen, so it depends on canvas scale, aspect ratio and more

urban marsh
#

thanks for the help and the comment about using rectTransform and the anchors : I was wondering why my things where offset weirdly πŸ˜„

cosmic ermine
#

when making triangles in a mesh is it better to go clockwise or counter clockwise?

cosmic ermine
#

also when setting Mesh.MeshData.subMeshCount, is there any specific required time to set it, or can I set it directly before I call Mesh.ApplyAndDisposeWritableMeshData()?

magic parrot
#

why do i get this error : The referenced script (Unknown) on this Behaviour is missing!
UnityEngine.Resources:LoadAll<MoveBase> (string)
ScriptableObjectDB`1<MoveBase>:Init () (at Assets/Scripts/Util/ScriptableObjectDB.cs:10)
GameController:Awake () (at Assets/Scripts/Gameplay/GameController.cs:18)
there are the classes : using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Move", menuName = "Creatures/Create New Move")]
public class MoveBase : ScriptableObject
{
public string name;
public string description;
public CreatureType type;
public int power,
accuracy,
pp, priority;
public bool alwaysHits;
public MoveCategory category;
public MoveEffects effects;
public List<SecondaryEffects> secondaryEffects;
public MoveTarget target;
}

[System.Serializable]
public class MoveEffects
{
public List<StatBoost> boosts;
public ConditionID status;
public ConditionID volatileStatus;
}
[System.Serializable]
public class SecondaryEffects : MoveEffects
{
public int chance;
public MoveTarget target;
}

[System.Serializable]
public class StatBoost
{
public Stat stat;
public int boost;
}

public enum MoveTarget
{
Foe,
Self
}

public enum MoveCategory
{
Physical,
Special,
Status
}

somber nacelle
#

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

cosmic ermine
thin aurora
#

Click the message and it shows you the missing script. Replace it with the correct script

#

You probably renamed it so Unity has no reference to it anymore

#

Also !code next time you paste 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.

magic parrot
#

ye , thats what i thought, didnt work, but it works now

#

oh, oke

#

thanks for trying to help anyway

abstract ivy
#

hmm anyone know how to load TMPro.TMP_FontAsset from resource to edit it, my issue is atm that when i try to do using TMPro it says it does not exist. WHen i ResourceLoad and Debug.Log it says TMPro.TMP_FontAsset, tried loading using generic FontAsset but then i got null

woeful dagger
#

hello everybody, i try to use a websocket in unity (client) my server is node js. it's working in editor but not in my browser (in build)
i try with System.Net.WebSockets; and WebSocketSharp

pseudo zodiac
#

@potent sleetI have another question about my quest system if you don't mind.
Basically, I have implemented the system as you suggested but I have a problem: I have my Quest in a list in my QuestManager, however these can't be MonoBehavior and so I can't for example do my onLoadScene function(which is called by my QuestManager) with calls like FindObjectOfType<> or GetComponent<> inside. What am I doing wrong?

rustic ember
#

Is it faster to write cs myInt2 = myInt + myInt than cs myInt2 = myInt * 2 ? Or does the compiler fix it? Or does it just not make a difference?

cosmic rain
#

The compiler would probably optimize the multiplication to addition.

simple egret
#

Yep, exact same on output machine code

cosmic rain
#

Either way, it's not something you should even be bothered about.

simple egret
#

Indeed, there's no significant difference. Try catching bigger performance hogs like repeated uses of Find and GetComponent

rustic ember
thin aurora
#

Sharplab

potent sleet
gray thunder
#

You're trying to access something you haven't assigned in the inspector

pseudo zodiac
gray thunder
#

They can still be MonoBehavior?

pseudo zodiac
#

No they can't otherwise I cant make a list of all my Quest in my QuestManager.

heady iris
#

I don't understand.

rain minnow
odd pecan
#

Is it possible to edit this in game ? or through script

heady iris
#

sure

#

AddKey, MoveKey, RemoveKey, SmoothTangents

odd pecan
#

oh thanks.

lethal plank
#

oh ok thanks

#

but i cant find any xd

pseudo zodiac
rose token
#

I'm trying to make a pickup script in unity. When I walk over a weapon I want it to be placed in the players hand. My current attempted solution was to parent the weapon to the lowerarm of the player. But the scale and rotation is all wrong when I do this. Also I seem unable to rotate my weapon to the right angle

#

This is my code

public void OnTriggerEnter2D(Collider2D col)
    {
        // Pickup gun
        if (col.gameObject.CompareTag("Player"))
        {
            Shooting shooting = col.gameObject.GetComponentInParent<Shooting>();
            if (shooting.holdingWeapon) return;
            

            this.transform.position = shooting.LowerArm.transform.position;
            this.transform.parent = shooting.LowerArm.transform;
}
#

result

heady iris
#

does your player have any non-uniform scaling?

#

i.e. scaling that isn't 2,2,2 or 0.5,0.5,0.5 or whatever

static matrix
#

RuntimeNavMeshBuilder: Source mesh Cylinder.001 does not allow read access. This will work in playmode in the editor but not in player

How can I fix this? I genuinely have no idea

heady iris
#

ah yeah, I ran into this recently

#

and it did, indeed, not work in the player!

#

so you're trying to generate a nav mesh at runtime

static matrix
#

yeah, because I have a procedurally generated level

rose token
heady iris
#

if you tell it to use render meshes, not colliders, the meshes will need to be marked read-write

#

I'm not sure if you can mark the built-in meshes as read-write..

static matrix
#

its not builtin

heady iris
#

o right

static matrix
#

where would I mark that?

heady iris
#

Cylinder.001

#

that's totally from Blender

#

anyway, go to the mesh asset

static matrix
#

yeah lol

#

k

#

go on

heady iris
#

you'll want to tick Read/Write

static matrix
#

I dont see that

heady iris
#

This will keep an extra copy of the mesh data in main memory, iirc

#

Show me the inspector.

static matrix
#

nothing to click here

heady iris
#

ah, I mean the asset itself

#

not the assets it contains

static matrix
#

ahhh

#

ok

heady iris
#

i think i need better names for those two concepts

static matrix
#

let me try and find that

#

ahaaaa

#

ok

#

thank you

heady iris
#

np

static matrix
#

lets see if not break

#

ok yeah, just need to do that for all imported models

#

then the thing should work

#

next step is solving the freezeframes whenever a new chunk is genned and generates the navmesh

heady iris
#

you can select many assets and check the box all at once

static matrix
#

yeah, I only have 2 rn so it isnt that bad

static matrix
heady iris
#

i don't know too much about runtime navmesh generation yet

static matrix
#

well I'm boiling it down to "Laggy thing happens and suspends running"

#

so if I try coroutines maybe it wont suspend

heady iris
#

if the function that builds a navmesh returns after the navmesh is built, coroutines will not help

#

you can still hang the game from a coroutine

#

coroutines are not magic; they're just capable of yielding to suspend execution

static matrix
#

ok mayb async then

heady iris
#

ah yes

#

UpdateNavMesh(NavMeshData)

#

AsyncOperation is just a coroutine that peeks at an async operation to see if it's done

static matrix
#

time to learn ✨ Threading ✨

rose token
#

Can I get some help please?

static matrix
#

hmmm

#

idk

rose token
static matrix
#

not sure

fiery shell
#

if you parent something to another transform, that child will then use the parent scale as their reference, which means a non uniform scaled parent will cause weird scaling and rotation in their child. Usually, if it is absolutely essential to scale a rendered object via the transform, people tend to parent it put the renderer as a child to the uniformly scaled transform that is then used for logic animation etc.

#

So the first step to solve your warped gun issue is to make sure the transform you are trying to parent it to is uniformly scaled (as in all three numbers in the scaling vector have the same value)

static matrix
#

zyesss it worked

#

perfectly

#

the first time

thick bough
# rose token Been waiting for 10 minutes now

You can't parent it directly under the hierarchy when you have it scaled like you do. you have other options like using a script to copy position and rotation from another transform in Update

#

Alternatively reorder your hierarchy like Christopher is saying

heady iris
#

non-uniform scaling is, in general, The Devil

#

it's okay for "leaves" -- transforms that have no children

thick bough
#

Ah sure, nice!

rose token
#

Could I get an example of how to use the ParentConstraint

rain minnow
west lotus
heady iris
#

i remember it being a little confusing to set up a constraint via script

#

here's how I configure a LookAtConstraint

#
void Awake()
    {
        target = GetComponentInParent<Entity>();
        health.target = target;
        lookAt.AddSource(new() {
            sourceTransform = Camera.main.transform,
            weight = 1f
        });
        
        lookAt.constraintActive = true;
    }
rose token
#

That works like a charm with the ParentConstraint

#

Thanks a lot guys

heady iris
#

i use ParentConstraint to get around how VRChat scales your head down really tiny

#

it's handy

rustic ember
#

Why can't I have two variables with the same name in different cases in a switch statement?

heady iris
#

oh lord, switch statements...

#

the tl;dr is that a switch statement is one big block

#

notice how it's all wrapped in a single pair of curly braces

#

However, there's nothing stopping you from doing this:

#
        switch(Time.frameCount) {
            case 1: {
                int x = 3;
                break;
            }
            case 3: {
                int x = 5;
                break;
            }
        }
#

in fact, you can slap down block statements wherever you want!

#
{ { { { { { { { { {
  print("hi :)");
} } } } } } } } } }
#

You usually use them after if because if only affects the next statement

#

A block statement is a single statement that contains several statements

#

thus letting you execute all of the statements in the block if the conditional is true

#

this is why they're optional for one-liners

#
if (foo)
  bar();

if (foo) {
  bar();
}
#

both of these have one statement after the if statement

strong cloud
#

I wonder what the performance impacts are of one versus the other, if any

heady iris
#

all of this gets chewed up by the compiler

#

it just needs to know, logically, what stuff should be skipped if the conditional fails

#

the IL (intermediate language) has no notion of "statements"

lone zealot
#

hey everyone. so I was wondering if I can have a child class not having to write a redundant line of constructor...
i.e. parent is

class P {
  public P(int a){}
}
``` and child is
```csharp
class C:P {
  public C(int a) : base(a){}
}```
is there a way to escape this insanity?
#

why can't the compiler just realize that when I don't write anything for the child, i want it to use the parent's constructor?

#

fyi this gives error

class C:P {}```
heady iris
#

them's the rules

lone zealot
#

three lines of redundant code.

heady iris
#

yeah...

#

look, at least we're not writing Java :p

lone zealot
#

yeah youre right. should be greatful

heady iris
#

i used to love Java, back in college

#

🫠

#

C# is just Cooler Java, when you think about it

lone zealot
#

if we factor this out, that is (the blue lines are redundant but forced)

#

we could use required and initializers in modern C# versions. but not in Unity's old C#

lone zealot
heady iris
#

I like ummm the uhhhhhhh

#

the uhhhhhhhhhhhhh

#

well it was a managed runtime

#

java was like sweatpants

#

i say, as i sit in my bedroom, wearing sweatpants

#

(i'm sick ok)

lone zealot
#

it's just the Java syndrome kicking in. you'll be alright after a few more lines of C#

heady iris
#
crux@Fens-MacBook-Pro Scripts % find . -name "*.cs" | xargs wc -l | tail -n1
    5031 total
#

just a few more lines bro

lone zealot
#

i believe in you

river wigeon
#

Something really weird is happening. I add 7 elements to a list in the editor but when I debug the list it's got 0 elements in it

heady iris
#

is it getting reassigned somewhere?

#

e.g. set to new() in Awake or Start

river wigeon
#

I don't think so

#

I'll post

#

it's a private field too

heady iris
#

hmm, I wonder if it has something to do with multiplayer

river wigeon
#

how so?

heady iris
#

[hands waving around]

heady iris
#

but I wouldn't expect that, hmm

river wigeon
#

this class works everywhere else fine

#

and if I set this state to be the first state in the state machine it works fine

#

that's the console

#

so there are definitely 0 elements in the list

dusk apex
#

When do you call onEntry?

river wigeon
#

that's the state in the editor, with 7 transitions in the list

river wigeon
dusk apex
#

The code shown won't help us. It'll only tell you/us where you've printed the value.

river wigeon
dusk apex
# river wigeon

Does the class have further code and any that changes the List?

#

Anything related to the List.

river wigeon
#

I'll send the full class, but it shouldn't change the list

dusk apex
#

Else it's an empty list if you've not added-to/modified the List

#

Which is important to be considered

river wigeon
river wigeon
dusk apex
#

Maybe this is referring to a different object and not the one you've posted above.

#

Try printed the name of the object.

river wigeon
#

omfg

#

you're right

dusk apex
#
Debug.Log($"The object in question is {name}", gameObject);```
river wigeon
#

I accidently have 2 playPolicyState

#

and had the state transition going to the second one

#

omgg

#

thanks

#

I'm dumb

dusk apex
#

Well, you'll be able to move on now UnityChanThumbsUp

river wigeon
#

yes, thank you. This has been a headache

#

it's always the little things huh

heady iris
#

aha, that'll do it :p

#

passing the object to the second arg of Debug.Log is super useful

full rune
rustic ember
heady iris
#

you're welcome!

wide fiber
#
  if (safezoneCollider.bounds.Contains(PlayerHit.point))
            {
                // Player is inside the safezone, do nothing
            }
            else if (Physics.Raycast(transform.position, RaycastDirection, out RaycastHit Playerhit, VisionRange, PlayerHit))
            {
                this.VisionConeMaterial.color = new Color32(255, 0, 0, 255);
                onSpot?.Invoke();
                Debug.Log("Player detected");
            }```

hi. why my "PlayerHit.point have error? 😦
#

the point have error

heady iris
#

Provide the actual error message.

rustic ember
#

How?

heady iris
#

What is the error

#

We can't tell you anything without seeing the error.

rustic ember
heady iris
#

and give us a paste with the code in it

#

I know that you can get some weird line numbers when dealing with coroutines

#

It has to generate a whole class to store the state of the coroutine

rustic ember
heady iris
#

hence that <ChangeTurn>d_18 thing

mellow sigil
#

There's a bug in the compiler which causes it sometimes to have index out of range errors point to the end of the block that contains them

heady iris
#

interesting

rustic ember
#

I just gave up lol

#

Not this time though

#

It happens before line 24

#
        Debug.Log("Reached for loop");
        for (int i = 0; i < gridPositions.Count; i++)
        {
            manager.tiles[gridPositions[i].x, gridPositions[i].y].controller.EnableTileSelect(moveTypes[i]);
        }
        #endregion

        Debug.Log("Reached while true");``` It's in here somewhere
mellow sigil
#

either moveTypes is smaller than gridPositions or manager.tiles doesn't contains some of the positions

rustic ember
#

You are right

#

I fixed it. Thank you πŸ™

vast wyvern
#

Good morning everyone πŸ™‚

Wanted to inquire- has there been any changes or open issues regarding saving w/ persistantDataPath coming from Unity 2020 lts to 2021 lts? The plugin I am using stores assets onto the persistantDataPath, ex: AppData/LocalLow/CompanyName. In the new engine, some files can be written correctly to disk while others- such as a texture, model, and photo files- no longer write correctly. Previously on the older engine, all files would write to disk successfully from an API call and download. On the new engine, this process does not start, presumably because it is getting stuck? No errors are caught nor does it exit the program, it just loops forever. The API returns 201 so its making a connection, just not initiating the download process.

Nothing has changed between these projects besides their engine version. I am searching through the code to see if there is a particular place it could be getting stuck but I am not sure where to break - I have been going through the code line by line with the debugger and have not hit where its getting stuck. If anyone is familiar, I am using AvatarSDK Cloud UMA Plugin 2.4. Overall, I am mostly trying to see if there are possibly external changes to the engine that could have disrupted this process to reconcile with the code. If anyone has any advice on how to debug this, its all welcomed. I have researched this to the best of my ability and did not see any open issues or changes that could match these symptoms.

tepid river
#

hello, it seems like my new project somehow doesnt have any realtime shadows.
im in the 3d urp preset, so far i only have disable ambient light.

heady iris
#

does the sun have shadows turned on?

valid vale
#

Hi all, I've got a question regarding UnityEvents. Is there a way to pass in both a dynamic parameter and a static parameter that's been set in the inspector? I haven't been able to get that to work directly, and I've toyed around with setting up a custom struct to allow me to but I can't come up with anything solid so far. Does anyone have any ideas?

jaunty sleet
#

Could someone check my code here? I have an array I am trying to use that I have set to size 5 but it says index 0 is out of bounds??? I don't know what's going on in it. The array is declared on line 39, and I try to use it on line 300. https://codeshare.io/QnN03R

heady iris
#

you mean you use it on line 302?

uneven dagger
#

So im trying to make an andriod game and wanted to test out the InputSystem. What im trying to do is when the player touches the screen a joystick appears on their finger and if they move their finger the joystick will also move. Ive deleted my code multiple times because I couldnt get the joystick to move when the player moved their finger. Any advice or documentation anyone can link me too would be extremely helpful.

leaden ice
leaden ice
#

you can thus pass any number of parameters you want

heady iris
#

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

heady iris
#

please use a paste site for big blocks of code

strong ravine
#

okay thanks

jaunty sleet
heady iris
#

the array is non-serialized, right

#

yeah, it's private

#

if it was, then it could have some other random size

jaunty sleet
#

Yeah, it a private array I am using internally

#

U can see I declare it as string[] behaviorParameters = new string[5];

#

So how is it possible for index 0 to be out of bounds?

heady iris
#

behaviorParameters[1] = "1"; is line 302

#

that's index 1, not 0

#

can you show your error

jaunty sleet
#

Yeah, it's the same with index 1

#

1 sec

#

IndexOutOfRangeException: Index was outside the bounds of the array.
(wrapper stelemref) System.Object.virt_stelemref_sealed_class(intptr,object)
LevelEditor.OnGUI () (at Assets/Scripts/LevelEditor.cs:302)
UnityEditor.HostView.InvokeOnGUI (UnityEngine.Rect onGUIPosition) (at <6a5b55f2e18b419e9faedac06ac6af94>:0)
UnityEditor.DockArea.DrawView (UnityEngine.Rect dockAreaRect) (at <6a5b55f2e18b419e9faedac06ac6af94>:0)
UnityEditor.DockArea.OldOnGUI () (at <6a5b55f2e18b419e9faedac06ac6af94>:0)
UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <171d8a8f3bd84fa7b9eb1f330018a789>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

#

@leaden ice Could u look at this if u have time? I have no clue why I am having this issue with basic stuff like array size lol #archived-code-general message

rain minnow
ocean river
#

hey. i need help, i cant find the "project settings" documented everywhere.
i only have these sorta settings

#

dammit messed up the screenshot

ocean river
#

im using a version that supports new 3ds.

leaden ice
#

so what's the issue exactly

#

what are you expecting to see and what are you seeing instead

ocean river
#

i cant find these playmode editor things

leaden ice
#

it's all under the Player settings

ocean river
#

oh thanks

leaden ice
#

it's the same menu

#

just presented differently

ocean river
#

you sure i cen edit the playmode configurations or something there

#

i want that reload scenes option

leaden ice
#

what reload scenes option

ocean river
#

dis

leaden ice
#

That's clearly under the "Editor" section

ocean river
leaden ice
#

That being said it either:

  • Might not exist at all
  • Might be in a different place

since you're looking at a much older version of Unity

ocean river
#

then i would have another question...
can i detect scene change in a persistent object?

leaden ice
#

wdym by "persistent object"

ocean river
#

ah

#

its created in every scene, if it does alr exist, destroy recreated copy

#

its always there and doesnt get destroyed

flat willow
#

So i declared an action:

 public event Action OnJump;

and whenever i try to call the action (with OnJump()) it results in a NullReferenceException, how could I fix this?

leaden ice
#

is the typical approach

#

You will typically get an NRE if you haven't assigned any subscribers to the delegate and you try to invoke it

#

note this is basically short for:

if (OnJump != null) OnJump();```
flat willow
#

Oh alright

heady iris
#

yep!

somber ether
#

This may be an odd question. How do I save multiple ints or some other save method to playerprefs that can be split up. I am making a shop, but need to toggle each button to unlocked or not, I dont want to have a spam of prefs since the shop sells like 50 things. This is local saved to reduce database calls

heady iris
#

There's nothing wrong with having many entries in PlayerPrefs

#

especially just 50 things

somber ether
#

That means my unity inspector will have 50 int variables, and 50 if else statements...

heady iris
#

well, you probably want to abstract that a bit...

#

you'll have a list of 50 item definitions somewhere

somber ether
#

I was hoping for some method like saving 10000100101 and then grab the 0 or 1

#

similar to an array

heady iris
#

you could pack it all into a bit field, sure

#

that's perfectly doable

soft shard
somber ether
#

code tho?

somber ether
cobalt elm
#

So after a couple changes I made (pretty much unrelated to this). This method is being called twice really fast for no reason. I am only pressing the button once? it was working a minute ago. Any help is appreciated thank you!

         
        pauseAction = input.actions.FindActionMap("Player", true).FindAction("Pause", true);
        pauseAction.performed += context => CheckPause();
        
        ////////

        public void CheckPause()
        {
            if (!GameManager.Instance.matchPaused)
            {
                GameManager.Instance.PauseMatch();
                MenuManager.Instance.Load("Pause");
            }

            else
            {
                GameManager.Instance.ResumeMatch();
                MenuManager.Instance.UnloadAll();
            }
        }
soft shard
somber ether
heady iris
#

imagine you have a setup like this

somber ether
#

Code example?

heady iris
#
public class ItemDefinition {
  public string identifier;
  public float cost;
}

List<ItemDefinition> items;
#

you would save whether or not you have unlocked each of the items, using the identifier as the key

#

maybe you'd keep it in a Dictionary<string, bool> in-game or something

#

to save it, you'd iterate over that dictionary, and, for each key, write the corresponding bool into a playerpref (using 1 for true and 0 for false)

#

to load it, you'd go through all the item definitions and try to get an int based on its identifier

#
foreach (var key in itemStatus.Keys) {
  PlayerPrefs.SetInt("Unlocked-" + key, itemStatus[key] ? 1 : 0);
}
#

something like that for saving

somber ether
#

Checked a video and it requires creating a new public function for each 50 items

heady iris
#

what?

somber ether
#

for toggling the object on and off or something

simple egret
#

Not if you use a collection like the Dictionary here

leaden ice
heady iris
#

you write the logic once

#

then you just apply it for every item

#

this is fundamental to...game programming in general, really!

somber ether
#

thats what I mean, you want me to create a function for each item

heady iris
#

no, I do not.

#

What did I say that made you believe that? maybe there is something unclear.

somber ether
#

apply it for every item

simple egret
#

As long as you manage to bind one item of the collection, to one item of your UI for example, it can be done all at once. Like with the foreach loop

somber ether
#

You are giving me a lot of terms, but not an example, I have to google each of these

heady iris
leaden ice
heady iris
#

you do the same thing for every thing in the list

somber ether
#

you mentioned bit fields, so im watching a video on that but it doesnt seem to be the right thing

heady iris
#

I do not think it is a good choice.

simple egret
#

Sample, assign a new value to a list item

void EnableItem(int index)
{
  list[index] = true;
}
somber ether
#

id prefer prefs

molten crane
#

Do you know where I can file request for In app purchases plugin to have assembly definition?

simple egret
#

It's not really the use of PlayerPrefs though, as its name suggests it stores preferences, like resolution, graphics quality, etc. You're better off saving that to a file.

#

Reading is one line of code, same for writing

somber ether
#

its mobile

simple egret
#

No problem. That also has filesystem access

somber ether
#

they usually have permission issues

cobalt elm
#

nvm, im writing a bunch of spaghetti code and i just deleted some stuff πŸ‘

simple egret
#

Each app has its dedicated storage location created, when it's installed

#

Under Application.persistentDataPath

somber ether
#

Maybe I can save a list to binary file

simple egret
#

Or JSON, whatever works for you. No BinaryFormatter though, it has security vulnerabilities and is unsafe to use on unverified serialized data

somber ether
versed marsh
#

this is quite possibly the worst code i have ever written that actually functions

heady iris
#

i am genuinely confused by this statement

simple egret
somber ether
#

json uses too many brackets

heady iris
#

wait, .root exists??

heady iris
#

the more you know

#

nice

simple egret
#

Yeah it's nice to check if you have a parent or not, transform == transform.root

versed marsh
pliant sapphire
#

Hi everyone! I have my player to have a Shield in front of him with box collider and different layer and tag from player. when player click RMB. But when it collides with an enemy it still takes away my health and I dont really know why cause it shouldnt do that based on my scripts. This is my Health script: https://hastebin.com/share/humemiyixu.csharp This is Script to take damage from a player when collision happens:https://hastebin.com/share/aforebepag.csharp This is player attack script where shield using is:https://hastebin.com/share/uyelerajez.csharp

leaden ice
versed marsh
#

wont work since the item its checking for is constantly being added and removed

leaden ice
#

and/or make a variable for it.

#

Code like this that relies on the hierarchy being arranged in a certain way is begging for difficult-to-debug bugs later on

#

when you inevitably rearrange the hierarchy

heady iris
#

yes

#

you will experience immense pain

versed marsh
#

yeah i will likely change it but for now i am too lazy and stubborn

heady iris
#

I prefer to just do GetComponentInParent as long as I know that the thing will always be a child

versed marsh
#

thats a problem for future me

heady iris
#

the UI system in one of my games has lots of components that all look for the UI manager by getting a parent component

pliant sapphire
wild hamlet
#

Hi I'm working on a Multiplayer project with Netcode for GameObjects. I'm trying to make a rigidbody object but it moves laggy and unnatural in clients.

I added Network Object, Collider, Rigidbody, NetworkRigidbody and Network Transform to my gameobject

heady iris
#

the built-in components for this are going to be laggy looking

#

they don't do some of the more advanced stuff that makes modern multiplayer games smooth (like client-side prediction)

#

for example, NetworkRigidbody is only simulated by the owner of the object

#

for everyone else, it's kinematic

wild hamlet
polar marten
#

what is the game?

wild hamlet
#

It's just and picking up and dropping items

polar marten
#

and does this have to be over the internet or just the LAN?

#

for the sake of prototyping

polar marten
wild hamlet
wild hamlet
polar marten
#

and how far along are you?

wild hamlet
polar marten
#

okay well i guess you can fiddle with the interpolation settings

#

is that the only thing you want to know about?

#

yesterday someone asked about making a networked fps and it was really difficult to talk about so i am pretty spent on this issue. it is way harder to make internet networked FPS experiences in unity than it appears.

wild hamlet
#

yeah I don't have problems with other things for now

#

I was going well but then i noticed object was lagging/jittering

leaden bluff
#

if anyone has a moment i need help with smth

polar marten
polar marten
#

you have a knockbackForce *= damping line

leaden bluff
wild hamlet
polar marten
#

like here is what you think the difficulty is:
1
and here is what the difficulty actually is:
1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111

polar marten
#

you can print it too

#

and see how knockback changes

wild hamlet
#

it may be but I'm trying to learn why would i just drop off the game because it has difficulties

leaden bluff
#

alr thanks

leaden bluff
#

i want the speed that the player is being knocked back at to gradually decrease each time it gets knocked back, but i dont want seperate knockbacks to differ from each other if that makes sense

cerulean oak
#

is there any way to cheat the number that DateTime.Now returns, for debugging purposes?

#

other than changing the pc time

#

wich is I guess what i'll end up doing

somber ether
#

Whats the code to read json or loop through entries? I used entries.Add(new InputEntry(producttype.ToString(), 1)); on each item purchased, now what I need is all of them who have 1 or data entry at all will have a gameobject enabled

#

I assume I will have to add every button to a serialize field

#

Thats the file managing class (got it from tutorial) but they didnt show usage of it

pseudo zodiac
#

does anyone know why my Couroutine stop at the yield return and doesnt execute the StartCoroutine at the end ?

IEnumerator OnCompleteAttack(bool succeeded)
        {
                success = succeeded;
                if (success)
                {
                    Interface.SetDialogText("Attack succeeded !");
                    
                    DecreaseEnemyAppreciationBy(10);
                    yield return new WaitForSeconds(1);
                    Debug.Log("marche ta mere1");
                }
                else
                {
                    Interface.SetDialogText("Attack failed !");
                    Debug.Log("marche ta mere2");
                    yield return new WaitForSeconds(1);
                }
                Debug.Log("marche ta mere3");
                StartCoroutine(EnemyTurn());
                
                yield return null;
        }
latent latch
#

Put some debugs after you start the coroutine and inside of EnemyTurn

pliant sapphire
#

Does anyone know why my knockback doesnt work on my enemy, this is enemy take hit script: https://hastebin.com/share/pitabodosu.csharp

pseudo zodiac
latent latch
#

Instead of yield return null, try yield return StartCoroutine(EnemyTurn());

#

I expect it be a scoping issue, but I still think the coroutine would live on the mono somewhere. I forget exactly

pseudo zodiac
#

My IEnumerator is a local function is that a problem?

#

Like here is the full function

#
private IEnumerator PlayerAttack()
    {
        bool success = false;
        
        attackMenu.OpenMenu(Player, OnSelectAttack);

        void OnSelectAttack(AttackObject a)
        {
            if (a == null)
            {
                return;
            }
            Debug.Log("Selected attack");
            StartCoroutine(performAttack.StartAttack(a.input.sequence.ToList(), 15, OnCompleteAttack));
        }
        
        IEnumerator OnCompleteAttack(bool succeeded)
        {
            Debug.Log("123");
            success = succeeded;
            if (success)
            {
                Interface.SetDialogText("Attack succeeded !");
                
                DecreaseEnemyAppreciationBy(10);
                yield return new WaitForSeconds(1);
                Debug.Log("marche ta mere1");
            }
            else
            {
                Interface.SetDialogText("Attack failed !");
                Debug.Log("marche ta mere2");
                yield return new WaitForSeconds(1);
            }
            Debug.Log("marche ta mere3");
            
            yield return StartCoroutine(EnemyTurn());
        }

        yield return null;
    }
latent latch
#

remove the return null

pseudo zodiac
#

It makes an error if I return nothing

latent latch
#

oh yeah you got it nested uh

pseudo zodiac
#

yeah

#

is that a problem?

latent latch
#

I feel like it should be fine, but I'm rusty at them. I'd probably need to fool around with it for a bit to refresh myself.

#

Because even if the first coroutine returns, your other (inner) coroutine should still be running

pseudo zodiac
#

I dont know what to do

leaden ice
#

And typically if your coroutine is not resuming from a yield it's because the GameObject it's running on was destroyed or deactivated

swift falcon
#

I did something horribly wrong in my code didnt I

#

I dont even understand

heady iris
#

What are you trying to download?

swift falcon
#

lmfao

heady iris
#

virus detection is...messy

swift falcon
#

Yeah

heady iris
#

it's very likely that you just randomly wound up with something that looks vaguely like a bad thing

swift falcon
#

Does it scan what the application does? or something like that

heady iris
#

it's a real rat's nest of different techniques and signatures

#

one thing that comes to mind is flagging things that appear to be, say, starting other processes, or downloading files

#

oh hey (:

#

perhaps that's what is making it mad

swift falcon
#

Oh yeah, I didnt include that but I did include a File.Create

#

But that usually doesnt do anything for the virus detection, ive done it before

leaden bluff
#

its just been on my to-do list for a while but i have no idea how to fix it

swift falcon
#

Okay buddy

Thats def not in my app πŸ’€ @heady iris

heady iris
#

they're probably both seeing the same (wrong) signature

swift falcon
#

Damn

#

ill search about this thing

ocean river
#

this may be a basic question, but i want the spotlight to be NOT smooth
just a little, but it should clearly be a circle.

heady iris
#

i forget the name of the field you want

#

angle something

ocean river
#

i changed angle and stuff but it doesnt affect it...

heady iris
#

Inner Angle (%), at least in the HDRP

ocean river
#

using unity 5.6.5

heady iris
#

ah

swift falcon
#

@heady iris I found out the Issue
Windows really doesnt like "GetAsyncKeyState(Int32 i)"

I put it in there for testing and experiments, it seems to think the program is a virus if that function is used

#

Quite annoying

heady iris
#

Interesting.

#

Oh

#

It's probably a keylogger thing.

leaden ice
swift falcon
#

Yeah I think so

#

Still sad if youre trying to use it for something not malicious

uncut path
#

Why am i getting an error, the audio is in it

heady iris
#

Something on line 44 is null.

#

Log the variables and find out.

uncut path
#

ill try that

mossy snow
#

likely func, AudioUtil doesn't seem to have a method called GetClipPosition in my version (2021.3.19f1)

heady iris
#

that won't cause an error on that line

#

the only thing that could be null (and problematic) is func

uncut path
#

I have a feeling its new System.Object

heady iris
#

i have a feeling it's not

#

log func

uncut path
#

k logging

#

it says null

#

i wonder why

heady iris
#

there ain't a function with that name.

#

there's a thing called GetPreviewClipPosition ...

uncut path
#

I tried

var func = type.GetMethod("GetPreviewClipPosition", new [] { typeof(AudioClip) });
heady iris
uncut path
fallen lotus
#

this code is causing an error:

Invoke(JoinLobbyByCode(joinCode), 2f);

The error is Argument type 'void' is not assignable to parameter type 'string' and its under the method

#

anyone know why? can invokes not pass a value in as a parameter? the function im trying to call is also an async. could that be the issue?

heady iris
#

this is not how you use Invoke

#

Invoke takes the name of a function

fallen lotus
#

OHHH

heady iris
#

you are calling JoinLobbyByCode(joinCode) and then trying to give its return value to Invoke :p

fallen lotus
#

omg i forgot

#

so it cant pass parameters

#

ive made this exact mistake before i just forgot lmao

heady iris
#

use a coroutine, yeah

slender basin
#

Assets\Movement.cs(5,38): error CS1003: Syntax error, ',' expected

#

ik this belongs in beginner but no one was responding please help

heady iris
#

the syntax for a class declaration is

#
public class ClassName : ParentClass {
  // ...
}
#

compare this to your code.

slender basin
#

so

#

i changed to semi colon to the end brakced

#

public Rigidbody RB3D;
is in they way

heady iris
#

you should not "change" the semicolon to anything

#

remove it

warm wren
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.

heady iris
#

yes, you still need to do this

slender basin
#

i tried

#

my unity hub isnt the same

simple egret
#

The config is done from an open Unity project, and the Visual Studio Installer program, as VS is already installed

#

Skip the steps you already completed, like the part where they use the Hub to install VS

#

Configuring your IDE is required to get help here

heady iris
#

everything from this point on is in the unity editor

slender basin
#

i dont get it.

heady iris
#

What do you not get?

slender basin
#

i cant find

heady iris
#

Can't find what?

#

The preferences menu?

slender basin
#

yes'

#

i have one

#

but it isnt the same

heady iris
#

are you still looking at the unity hub?

#

if not, are you looking at the Project Settings?

slender basin
#

not currently

heady iris
#

follow the instructions. Edit > Preferences

slender basin
#

im in my project

heady iris
#

not Edit > anything else

#

it's not "not working"; you have a compile error

#

what is the error?

#

ah, yes

#

it's because the method is a static method of GameObject

#

or Component

#

so, if your class derives from Component, you can just say FindObjectOfType directly

#

because it's implicitly like saying MonoBehaviour.FindObjectOfType

#

you just need to prepend GameObject. to that

slender basin
#

Common7/IDE

heady iris
#

np

slender basin
#

i just like wut

heady iris
#

where is this from?

slender basin
#

i need to get to Common7/IDE

#

its

#

in the instruction

heady iris
#

no, you need to select a version of Visual Studio that you have installed

#

if your version of Visual Studio is not listed, you did not follow the instructions.

slender basin
#

i have one installed version from 2019

weary depot
#

peeps

heady iris
slender basin
#

no ive had it since i started

heady iris
#

Does it show up in that dropdown list?

weary depot
#

I have to deliver an essay in like a day and have one simple question, up until incremental GC did unity use generational GC?

slender basin
#

this and browse is all i have

heady iris
slender basin
#

what

heady iris
#

Yes, I think you should uninstall your copy of Visual Studio and install VS 2022

#

then follow the rest of the instructions

heady iris
#

although, a generational GC is incremental

weary depot
#

I had the same impression but I read some articles stating something about mono NOT having generational GC hence so did unity in turn. But this helped, thanks!

fathom patrol
#

how do I change a [SerializedField]'s value from in another file

#

its too late and my brain is dying

heady iris
fathom patrol
#
[SerializeField] Vector2 maxPos;
    [SerializeField] Vector2 minPos;
    
    public Vector2 MaxPos 
    {
        get
        {
            return maxPos;
        }
        set
        {
            return;
        }
    }

    public Vector2 MinPos
    {
        get
        {
            return minPos;
        }
        set
        {
            return;
        }
    }

code rn

heady iris
#

It’s private.

#

(Since fields are private by default)

fathom patrol
#

but I public it in my code right

heady iris
#

You have properties.

#

Their set methods do nothing.

#

Both of them just instantly return.

fathom patrol
#

i should probably head to bed 😭

heady iris
#

you need to assign the value to something

#

(in a setter, the value you’re trying to store is called value)

slender basin
#

i dont get it i know i sound dumb bvut my unity hub install portion literally doesnthave an add button the onlyh option or upodate or any thing on my visual C is 2019

fathom patrol
heady iris
#

No, that is declaring a brand new variable.

#

Just set maxPos

fathom patrol
#
    public Vector2 MaxPos 
    {
        get { return maxPos; } set { maxPos = value; }
    }

    public Vector2 MinPos
    {
        get { return minPos; } set { minPos = value; }
    }
#

okay ill just head to bed and do this tomorrow since my brain cant even work out this simple stuff anymore

uncut path
heady iris
uncut path
#

is there documentation on Director Timeline/Animation programing?

#

this is the script that is giving me errors and im trying to fix it but it might be over my head and like @mossy snow mentioned AudioUtil might be depreciated

uncut path
#

if UnityEditor.AudioUtil was depreciated how do i look though the UnityEditor API, Library, or dll for an alternative?

#

I figured out how to poke at it.

steel vortex
#

Hey guys, have a problem, I put my player in a prefab folder because I have a dungeon generator and it spawns the player randomly and for that it has to be a prefab and the player needs in his script the camera but as a prefab I can't assign cameras, why? Or how do I fix this?

#

because This is a 2D roguelike game and he shoots in the direction where the mouse arrow is and for that he needs the camera.

#

okay

#

ah okay

finite hollow
#

Hey guys! I'm a little stuck with this thing I want to implement. I wanted a dynamic screen, wherein I push a button and the camera would pan to specific location. I was thinking of moving the camera with a lerp, where the startposition is where the camera is located and then the ending position is the targetposition, and I put it in a function that is then attached to the buttons onclick. ... Should I not have done that? Because it seems like every tutorial I've seen puts lerps in updates haha...

steel vortex
#

xD

uncut path
steel vortex
#

is that how it should be?

#

no I mean the punch animation

#

sorry i mean sword animation

#

ah okay, but looks nice

#

but even if I separate that, how do I do that with the camera?

#

nice

#

The lower camera should be assigned not the normal

#

Camera Movement works everything only the player does not turn to my mouse because it needs the camera

#

Followed some tutorial and then found this dungeon generator with the 2 cameras

#

both

#

good question

#
#

I did the tutorial and then found the generator and just copied it into my game

#

I have just tried to use one no matter which of the two, as soon as I remove one goes nothing more

cosmic rain
#

They're using Cinemachine. One is a virtual camera, the other one is an actual camera

#

That's how Cinemachine works.

#

It's a package for controlling the camera. You can google that.

steel vortex
#

In the "LevelGenerator" script I have to drag in the camera "CM vcam1" and in the cam is in there:

#

yea

#

And a tag then give the camera and assign that in the script and done?

#

google says that ```public Camera catchingCamera;

if (catchingCamera == null)
catchingCamera = GameObject.FindGameObjectWithTag("CatchingCamera").GetComponent<Camera>() as Camera;```

#

okay, iΒ΄ll try

uncut path
#

I'm trying to put AudioUtil back so i can use it but i cant find mono

#

i tried putting it in Assets but i got errors

#

and i cant find it when i type in

using UnityEditor.AudioUtil;

//or

AudioUtil _AudioUtil;
#

windows search didnt find anything

cosmic rain
#

"Put back"?πŸ€”

cosmic rain
#

Why would you want to put it anywhere? It's just for reference. The actual code is in the unity dlls

uncut path
#

how do i look at what is in the dll?

cosmic rain
#

You don't... I mean, I guess you could try inspecting the correct dll in the ide, but what for..?

#

What the heck are you trying to do?

uncut path
#

im trying to use this to scrub through audio so i can do facial animation
https://github.com/keijiro/AudioPreviewTrack

But this Line of code

var type = Type.GetType("UnityEditor.AudioUtil,UnityEditor");
var func = type.GetMethod("GetClipPosition", new [] { typeof(AudioClip) })
return (float)func.Invoke(null, new System.Object [] { clip });

Is giving me an error whenever i move the play head
Error

NullReferenceException: Object reference not set to an instance of an object
Klak.Timeline.AudioPreviewPlayable.GetClipPosition () (at Assets/AudioPreviewTrack/AudioPreviewPlayable.cs:49)
Klak.Timeline.AudioPreviewPlayable.PlayClip (System.Single time) (at Assets/AudioPreviewTrack/AudioPreviewPlayable.cs:62)
Klak.Timeline.AudioPreviewPlayable.ProcessFrame (UnityEngine.Playables.Playable playable, UnityEngine.Playables.FrameData info, System.Object playerData) (at Assets/AudioPreviewTrack/AudioPreviewPlayable.cs:30)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
#

and when i debug fun it returns null

leaden ice
uncut path
#

someone said AduioUtil is probably depreciated but i cant figure out how to take a closer look at AduioUtil or UnityEditor to find an alternative

cosmic rain
#

Try generating project files in unity - preferences - external tools with all the checkboxes above checked. Then you should be able to see the editor assembly in your ide. You can explore it to find the class you're looking for.

mossy snow
#

did you read the notice at that link? There's probably a reason it's 6 years since an update

uncut path
#

yah but theres got to be a way to get it to work today or make a better or new one.

leaden ice
#

Isn't... that what the notice is talkiing about?

#

That there's a setting to do this now?

uncut path
leaden ice
#

... did you not read it?

#

It's the very first thing in the readme in the link you sent

uncut path
#

sorry i just figured life is hard and there is never an easy option to anything ever

#

my bad

muted sonnet
#

my serialized field is just not showing up in the editor

#

it's a simple [SerializeField] private static Rigidbody _rigidbody

quaint rock
#

can not serialize static fields

muted sonnet
#

oh god I'm dumb

leaden ice
#

So weird that these come in waves like that

muted sonnet
#

lmao

uncut path
#

Thank you @cosmic rain, @mossy snow, @leaden ice
Sorry about wasting your time 😦

muted sonnet
#

just got back into it after years off

#

kinda remembering things slowly

#

I use rust mainly anyway, so C# isn't the most intuitive

leaden ice
#

Well this is more of a Unity thing than a C# thing

muted sonnet
#

yep

#

my mind just went

#

"global variable?"

#

"static."

mossy snow
#

Your bug probably isn't in this snippet. Look inside InventoryObject and see what it has in Container. Setting a breakpoint on line 25 of InventoryReader and working thorugh what that loop is doing and why will show you whatever is causing this

strange epoch
#

I need help with a bug in my game. Whenever the scene is reset the values of some variables are set to 0 or null. for example, when the game is reset, the player's speed is set to 0 for some reason. This has never happened to me before. I'm using github, I don't know if that could have anything to do with it.

cosmic rain
#

Did these variables have a different value prior to you pressing play?

plucky karma
leaden ice
olive shore
#

bruh does anyone know why googles giving me this despite me already having the snippet: <uses-permission android:name="com.google.android.gms.permission.AD_ID"/> inside of my android manifest?

undone remnant
#

Hey guys

olive shore
#

sorry, thanks

potent sleet
#

i mean if it works it works right ?

#

well you can firstly just probably do


        while (!loadingOperation.isDone)
        {
            yield return null;
        }```
#
 if (minLoadingTime > 0)
        {
            yield return new WaitForSeconds(minLoadingTime);
        }

        loadingOperation.allowSceneActivation = true;
#

the line yield return null after setting loadingOperation.allowSceneActivation = true is unnecessary

cosmic rain
#

I don't think there's a need for refactoring, but I think there's an issue with your waitTime and totalWaitTime.

potent sleet
cosmic rain
#

Maybe what Null suggested though.

potent sleet
shell scarab
#

Is there a way to determine if a urp decal projector is rendering without constantly checking the distance the player is from the decal β€˜bounds’?

latent latch
#

I would expect it to cull if the bounds are not* in camera view, or maybe I'm mistaken. Usually how it works with the vfx graph.

lost dove
#

Hi, I'm trying to use tweening (DotTween) to make my object move in a random direction on the screen, then come back and slam into a position quickly.
my code is as follows:

            if (targetPiece != null)
            {
                var captureDestination = pieceMoveDestination += new Vector2Int(UnityEngine.Random.Range(-1, 1) * 5, UnityEngine.Random.Range(-1, 1) * 5);
                var captureTween = DOTween.To(() => movingPiece.transform.position, x => movingPiece.transform.position = x, captureDestination, 1f);

                while (captureTween.IsActive())
                {
                    yield return null;
                }
            }

            // Standard movement
            var tweener = DOTween.To(() => movingPiece.transform.position, x => movingPiece.transform.position = x, pieceMoveDestination, 1f);

            while (tweener.IsActive())
            {
                yield return null;
            }```

my issue is that it goes out as expected, then teleports back to the original position and then slowly going to the final position.
#

Any ideas?

latent latch
#

There is a draw distance I know on the projector, but I'm not too sure if there's a sure way method to checking if it's being culled

glossy basin
#

Hello there, I would like to use the cellular noise from the unity mathematics package and preview it , however I dont know how to activate it; I want to preview this noise into a 2d texture but it uses a float2 instead of a float, so How do I render this ? standard noise is as easy as this

#

Nvm, it turns out it returns F1 and F2 from cellullar so you can use x or y value

plucky karma
#

Am I'm running into precision problems?

 private void OnDrawGizmos()
    {
        var pos = transform.position;
        var nearClip = _cam.nearClipPlane;
        var horzFrac= (Screen.width + 0f) / horizontalCount;
        var vertFrac = (Screen.height + 0f) / verticalCount;
        Vector3 screen;
        screen.z = nearClip;
        for (var x = 0; x <= horizontalCount; ++x)
        {
            for (var y = 0; y <= verticalCount; ++y)
            {
                screen.x = x * horzFrac;
                screen.y = y * vertFrac;
                pos = _cam.ScreenToWorldPoint(screen);
                Gizmos.DrawSphere(pos, size);
            }
        }
    }

revised for better naming convention.

undone remnant
#

hey can someone please help me with my code

obtuse cedar
#

i was told that I shouldn't rely on singleton too much
but I can't think of a better pattern to do this.

#

basically i want a pool of bullets

#

so i was thinking of making it signleton

#

so guns can quickly access that pool and recycle bullets

#

the only problem is if I want to access different types of bullets with different propperties i would have to make more pools
idk if this is a good approach

plucky karma
#

Otherwise, consider looking into Dependency Injection.

strange epoch
cosmic rain
strange epoch
#

No

latent latch
cosmic rain
# strange epoch No

What if you set it to some non 0 value, then close the project and open it again. Does it keep the value that you set?

strange epoch
#

It does, it only changes the value when the scene is reset during play

#

It doesn’t happen only with floats, if I assign a game object to a public variable, it is set to null when the scene is reset

plucky karma
strange epoch
latent latch
#

I think I looked at that, and unless it does something under the hood that does anything fancy, it's very similar to that of a singleton design

somber nacelle
#

unity's object pool isn't a singleton at all. but you can use it in a singleton

strange epoch
#

Load the current scene

leaden ice
#

Ok and is this script on a DDOL object?

strange epoch
#

What is a DDOL?

leaden ice
#

DontDestroyOnLoad

strange epoch
#

I don’t think it is, but I’ve never used that I this is the first time I’m having any trouble with this

leaden ice
#

You're going to have to show more information

#

Screenshots for example

#

And code

strange epoch
#

Ok

#

Here is a screenshot before hitting play

#

Here's during play before resetting the scene, everything works fine here

leaden ice
#

Ok go on...
Noting that some values have changed in screenshot 2 which means your script is changing them

#

Show the code?

strange epoch
#

ok

#

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

public class Movement : MonoBehaviour
{
// Start is called before the first frame update
//Author: Yatharth Padharia
//Code: To make player move
public float minfallspeed = -0.08f;
public float maxfallspeed = -1f;
public float moveSpeed;
private CharacterController control;
float t = 0.0f;

public float fallSpeed;
public float maximumFallingSpeed;
public float acceleration;
void Start()
{
    control = GetComponent<CharacterController>();
}

// Update is called once per frame
void Update()
{
    fallSpeed = Mathf.Lerp(minfallspeed, maxfallspeed, t);
    t += 0.5f * Time.deltaTime;
    //print(fallspeed);
    float horizontalInput = Input.GetAxisRaw("Horizontal");
    float verticalInput = Input.GetAxisRaw("Vertical");

    Vector3 direction = new Vector3(horizontalInput, 0, verticalInput);

    //Tied the movement to time (Andre)

    //Make player move in the direction they're looking (Andre)
    //Normalized horizontal player movement (Andre)
    control.Move(Quaternion.Euler(0, CameraController.horizontalMouse, 0) * direction.normalized * moveSpeed * Time.deltaTime);

    //Separated vertical velocity from horizontal movement (Andre)
    control.Move(Vector3.up * fallSpeed * Time.deltaTime);

    //Slowly make the player fall faster over time (Andre)
    maxfallspeed = Mathf.MoveTowards(maxfallspeed, maximumFallingSpeed, acceleration * Time.deltaTime);
}

}

leaden ice
#

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

strange epoch
#

sorry

leaden ice
#

I'd guess one or more of your other scripts are at fault

#

How's your slow time script work?
which script reloads the scene?

strange epoch
#

I'm not sure is a script, I just noticed now that a whole script disappears when the scene is reloaded

#

Here's is the script before hitting play

#

And here it is after reloading the scene

#

The WinState script disappeared

#

I think it might have something to do with the game object being a prefab

plucky karma
#

Cool! I got this working in code!

potent sleet
plucky karma
orchid bane
#

Why may I get a vector like this even though I Debug.Log myVector.normalized?
(-0.26, 0.00, 0.97)

mellow sigil
#

that is a normalized vector

orchid bane
#

Is it?

mellow sigil
#

yes

#

check the magnitude

orchid bane
#

Bad for me then, bug is in something else

candid trench
#
public class RotatingBody : MonoBehaviour
{
    public Vector2 RotatePoint;
    public float Angle;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        Vector2 v = RotatePoint - new Vector2(transform.position.x,transform.position.y);
        float length = v.magnitude;
        float rotationAngle = Angle * Time.deltaTime;
        float x = v.x * Mathf.Cos(rotationAngle) - v.y * Mathf.Sin(rotationAngle);
        float y = v.x * Mathf.Sin(rotationAngle) + v.y * Mathf.Cos(rotationAngle);
        v = new Vector2(x,y);
        transform.position = v;
    }
}

Im simply trying to have my sprite rotate around a point.
Its working, but its flickering between the sides of the point.

urban marsh
#

Hello everyone !
Is there a difference performance-wise between using fixedUpdate and Update in a script ?

somber nacelle
#

FixedUpdate does not run every frame. you should use it for physics related logic while using Update for most other stuff

rain dove
strange epoch
#

Yeah, that was it, but it still shouldn’t happen

#

And also when I assign a game object to a script it is set to null when the scene is loaded, is there a way to fix this?

#

Overriding the changes worked with variables like floats, but not game objects

rain dove
#

a prefab cannot hold another game object which is not part of the the prefab; u have to access that game object runtime;

#

u can assign it; but as soon as u will hit play it will loose its refrence;

#

@strange epoch

strange epoch
#

It works fine when I hit play, the problem only happens when I reset the scene

#

Would the same happen if the object wasn’t a prefab?

urban marsh
rain dove
#

i dont think so; havent tried this; let me check this;

somber nacelle
urban marsh
#

OK.

#

so it's more about doing "better movement" than "more optimized"

latent latch
#

It's useful to stick stuff like spherecasting and grabbing colliders in it since you don't want to be doing that every frame

rain dove
strange epoch
#

Reload scene

rain dove
#

okay it doesnt break; confirmed checking it; it keeps the refrence no matter what; im on 2019.4.20 lts

fathom plaza
#

Hi guys! Quick question, is it possible to have multiple instances of PointerEventData across different classes? Or would that produce conflicts?

sage latch
fathom plaza
#

Oh okay. But for EventSystem, would there be conflicts should I plan on multiple instances of such across different classes?

lone zealot
#

hi, is it alright to use reflection when building with IL2CPP?

#

I could try, but if anyone has before, i'd be glad to let me know

rain dove
# sage latch It's just a class so I don't see why not

id rather suggest to create a common controller for handling pointerevent data; for optimization purpose; as if too many of those classes are active and loaded; would impact performance; nothing else is the issue; and if mulitple events are trying to modify the attributes of the same gameobject that can be a potential problem ;if u handle that with care no issues with having multiple pointerevent data

lone zealot
#

(finding a value by a dynamic string. so no AoT string magic)

quartz folio
#

if something isn't found via reflection it has been stripped, and you need to indicate to keep it

fathom plaza
#

Thanks for the help, everyone!

lone zealot
quartz folio
#

Yes. Everything works unless something was stripped because nothing referenced it explicitly

lone zealot
#

ah, thanks πŸ™

strange ferry
#

Hello everyone, I was wondering if there's a way to add a dependency to a project to require a certain package, for example, I'm making a prefab that needs the 2D sprite package, do you guys know a way to tell the developer that it needs it to use the prefabs?

wet pumice
#

is System.Guid not serializable with JsonUtility?

cold parrot
wet pumice
thin aurora
# wet pumice is System.Guid not serializable with JsonUtility?

Probably not. You're better off using a better serializer such as Newtonsoft or System.Text.Json, because JSONUtility is very bad at doing the thing it's made for. I believe Newtonsoft has a package for Unity. Alternatively you can put the DLL of it in a Plugins folder in your project to use it. System.Text.Json is much more work to get to work.

strange ferry
#

Guys do you know if you can do a coroutine to execute in edit mode?

cosmic rain
mellow seal
#

Hey guys so i have a quick question

Should i define EnemyManager at start then use it on update

or use it in update like this?

EnemyManager.Instance.CanAttackPlayer();
leaden ice
heady iris
#

There's basically zero difference as long as you aren't scanning the whole scene for the EnemyManager or something

spiral ibex
#

If it's a small game, it doesnt matter. If it's a big game, consider caching it during Awake which would allow for you to extend/change it more easily in the future.

mellow seal
#

oh okey thank you guys very much

leaden ice
#

Caching during awake is going to potentially introduce script execution order issues

heady iris
#

indeed.

leaden ice
#

Presumably Instance is assigned in Awake

spiral ibex
#
EnemyManager manager;
void Awake(){
  manager = EnemyManager.Instance;
}
#

We are thinking this right?

leaden ice
#

Yes and if that runs before the Awake that assigns it?

heady iris
#

It depends on how you implement EnemyManager.Instance, I guess

spiral ibex
#

I would assume that Instance is lazy initialized

heady iris
#

If it's assigned by the EnemyManager during its own Awake call, you're going to have ordering issues

#

If it's lazy-initialized, then it oughta be fine.

leaden ice
#

And not very common

#

Relative to awake

spiral ibex
#

The other side of that coin is, imagine you have built a game where you have 50 psuedo singletons and want to migrate to a DI, now you have to fix hundreds, perhaps thousands of calls.

leaden ice
#

Such is the nature of refactoring code

spiral ibex
#

That's why I said If it's not a small game

thin aurora
#

The reference to EnemyManager.Instance already exists and you're "caching" the same reference

thin aurora
thin aurora
#

I would argue that this is a good way to do this because you abstract the access to Instance. This might be nice for refactoring later if you decide not to make EnemyManager a singleton but instead get an instance of EnemyManager from a collection of dependencies, for example.

heady iris
#

properties are a nice way to abstract it, yes

thin aurora
#

Yup, and in this case it will only try to get EnemyManager.Instance when you call it.

#

If, for some reason, you do want to cache it, you can make the property store EnemyManager.Instance in a manually defined backing field, and retrieve it from there with later calls.

coral kettle
#

in unity2D. I want to make it so when you enter a specific area it changes the references to things to be things in that area. my first idea is a trigger box collider that covers the area and use OnTriggerEnter. is there a problem with everything always being in a trigger? can it screw with other triggers?

gilded grove
#

Is there any advantage on Invoking movement via InputAction like ctx.action.ReadValue<Vector2>() as a coroutine instead of reading the value on Update()?

thin aurora
#

Also, you need OnTriggerEnter2D, not OnTriggerEnter

coral kettle
#

hmm

heady iris
#

use a coroutine when you need to perform an action across several frames with state persisting from frame to frame

whole steeple
#

Wall-sliding for Unity 2D

gilded grove
leaden ice
heady iris
#

more specifically, you should use a coroutine when:

  • you're doing a one-off action
  • the action needs to take place over several frames
  • the action requires state to persist from frame to frame
#

the advantage is that you don't have to manually persist that state

#

you just let the coroutine hang on to it for you between yield statements

#

in case that's too abstract, by "state" I mean any data that's needed to do the Right Thing: a coroutine that shrinks an object over time needs to store the start and end sizes, and also remember how far along it is, for example

#

Movement doesn't really fit any of those criteria

#

you're always doing it (or, at least, you just toggle it on and off), and you're always doing the same thing every frame

gilded grove
leaden ice
#

If you're getting an event pretty much every frame anyway

#

then it doesn't really make a difference

gilded grove
heady iris
#

I prefer to just read values directly every frame

leaden ice
#

For something like movement I prefer polling

#

for pressing a button, events are good

heady iris
#

I found it awkward to do

#
OnMoveInput(InputAction.CallbackContext context) {
   lastMove = context.ReadValue<Vector2>();
}
gilded grove
leaden ice
#

like joystick code especially

#

is super awkward as an event

heady iris
#

"polling" just means asking for the value yourself

leaden ice
#

much cleaner in Update

heady iris
#

versus "pushing" (?), where the input system tells YOU when something happens

#

(which is great for button inputs)

gilded grove
#

Great, this all adds clarity, thank you for the responses!

heady iris
#

np!

#

Pushing is often better because it means you aren't constantly spamming the input system / the server / etc.

honest sky
#

Just out of curiosity, if i have an Update, and i call a function twice within that update, does the function happen twice or only once?
i.e

void Update(){
  if(1 = 1) function1();
  if(2 = 2) function1();
#

i think its twice but since its per frame i dont know if it can be done twice per frame

heady iris
#

there is nothing special about Update

#

you'll get two function calls

#

(note that 1=1 is not valid syntax)

#

If that function MUST only run once per frame, I'd just move the logic to somewhere that only runs once

honest sky
#

also alright thanks

thin aurora
honest sky
magic harness
#

Hey boys. Need a quick fix for a problem im having right now.
I'm making a retro-style 2D RTS, and i have a map as an UI object, just an Image, sent on a world space canvas. On top of it i have some other screen-space ui objects.
I want to disable my mouse cursor clicking on the map when i interact with this other Ui objects. How would i approach this?

heady iris
#

how do you detect interactions with the map?

magic harness
#

Input.GetMouseButtoDown

heady iris
#

and then you read the current mouse position and do a raycast?

dim hinge
#

I Need someone that can help me making a unity battle system similar to undertale, there is someone? It will be very helpful, it's not that hard but i need help

heady iris
#

please don't repost the same question in several places

magic harness
magic harness
#

the program xD

heady iris
#

It sounds like you need to be able to detect when the mouse hits a UI element, and then bail out

magic harness
#

uhm... makes sense

heady iris
#

this might be useful

#

a graphics raycaster can tell you what your pointer was over

rustic ember
#

I have this thing: cs [System.Serializable] public class Vector2IntEvent : UnityEvent<Vector2Int> { }
I use it in a script: cs [HideInInspector] public Vector2IntEvent onPositionChanged;
What is the correct way to add a listener to onPositionChanged? I get a red line under ChangeListeners when I put nothing in the parenthesis

positionHandler.onPositionChanged.AddListener(ChangeListeners("WHAT TO PUT IN HERE?"));```
heady iris
#

what is ChangeListeners?

rustic ember
#

A method

heady iris
#

is that the method that you want to call?

rustic ember
#

Yes

heady iris
#

then just pass it directly to AddListener

magic harness
rustic ember
#
    public void ChangeListeners(Vector2Int _oldGridPos)
    {

    }``` It looks like this
heady iris
#

if you do this:

x.AddListener(MyFunction(/* ... */))
magic harness
#

so i have multiple graphics raycaster

heady iris
#

you're gonna try to call MyFunction, and then pass the return value from it to AddListener

#

which is void, in this case, which is impossible

rustic ember
#

Oh

heady iris
#

Yes, you're trying to invoke ChangeListeners with 0 arguments

#

you will get an error

#

even if you gave it an argument, you'll still get an error, since AddListener wants a function that takes a Vector2Int

rustic ember
#

What argument do I put? I want the Vector2Int that is passed with the Vector2IntEvent

heady iris
#

(and you'd be giving it void)

heady iris
#
x.AddListener(MyFunction);
rustic ember
#

So I just delete the parenthesis?

heady iris
#

Right. You are not invoking ChangeListeners here

#

you are passing it as an argument to AddListener

#

if you hover your mouse over AddListener, your IDE should show you the type of that function

rustic ember
#

IIs that always the case with UnityEvents?

heady iris
#

This is how it works for anything that expects a function as an argument, yes

rustic ember
#

Alright

#

That makes sense. Thank you

heady iris
#

Functions can be treated like objects in C#

muted sonnet
heady iris
#

we might say they're "first-class"

muted sonnet
#

there's nothing special about it

heady iris
#

meaning that they're treated just like any other types

#

in some languages, you can't just do something like

heady iris
#

return SomeFunction;

#

functions are "special" in some way

rustic ember
#

Oh okay

#

Thank you for taking the time to explain

heady iris
#

in C, for example, you can't pass a function as an argument (you have to pass a pointer to a function instead)

rustic ember
#

What do you mean pointer?

muted sonnet
#

(you just don't hear about it)