#archived-code-general

1 messages · Page 158 of 1

hasty haven
#

It ended up being a lot more complex and requiring way more steps but i love the way it looks

#

Had to generate 2 different lookup tables

ashen yoke
#

hm it may be possible to use a single shader with triplanar and 3d texture even for this case

hasty haven
#

I was thinking about generating some surface geometry like little pebbles depending on what it is

#

probably a second renderer

ashen yoke
#

that sounds like something you dont need to bake

#

(and also can be done on the shader)

hasty haven
#

Oh yeah, maybe a compute or vertex shader

hasty haven
#

There was one by i think AstroCat that looked very clean and was interactive

#

It would require some modifications to work with multiple players though

#

This looks very nice too

ashen yoke
#

doubt debris and clutter need to be syncd

hasty haven
#

Nope, at this point its only the byte array underneath everything

#

how its drawn can be on the client side

naive swallow
#

Any easy way in C# to give named values to the result that comes from an array like this?

(string caller, string func) = token.Split(".");

Essentially, I want to avoid using result[0] and result[1] and give them more meaningful names all in one line.

leaden ice
#

how pythonic of you

naive swallow
leaden ice
#

I don't think so, short of modifying the function to return a tuple

naive swallow
#

I've been bouncing between them and am saddened it doesn't work this way in C#

leaden ice
#

which you obviously can't here

naive swallow
#

Yeah, just wondering if there's anything I can do it because this error seems promising:

#

It's just that string arrays don't have a Deconstruct operator

#

Wondering if there's a namespace that gives it one?

leaden ice
#

idk if C# has that
you could write one with IndexOf and Substring

ashen yoke
#

what can cause a pod which has [SerializeField] string guid;
with ISerializationCallback,
to have a value in editor, but at runtime the string is empty?
its a scriptable, debugged, value is present in editor,
at runtime in OnAfterDeserialize the string is empty

naive swallow
raw coral
#

i need some more help. in my game you fly in the sky. i want the creatures that live in it to move even when you're not moving. like you can stay still, but the animals still move. how would i do that?

naive swallow
#

So if they don't move unless you're moving and you don't want that, get rid of whatever you did to make them do that

leaden ice
naive swallow
raw coral
ashen yoke
#

mistery, i can see in OnBeforeSerialize that the string is set to a value, at runtime its gone

pure cliff
naive swallow
pure cliff
leaden ice
#

I'm sure you can

#

but I'm too old school to know how to do that 😆

pure cliff
#

the best part is that you can do [n...^1] which is ❤️

leaden ice
#

The only one I'm proficient with is s[^1]

pure cliff
#

yeeee, I was so hype when that functionality was announced

#

no more myString.Length-1'ing

#

its really harshing my workflow when like half my stuff gets underlined as a warn/error when I have explicitly setup my editorconfig for it to be ignored :/

naive swallow
pure cliff
#

its like the IDEs are loading the .editorconfig file... and then promptly ignoring it in the actual editor o_O

leaden ice
#

not even sure what that is

pure cliff
leaden ice
#

there's a lightbulb thing in the bottom right

pure cliff
#

thats what the editorconfig file is 🙂

leaden ice
#

I see

#

I thought that stuff went in your home folder somewhere

pure cliff
#

it does yup, right next to the .sln and .csproj files

leaden ice
#

rather than being a project level setting

#

but those are in the project itself

pure cliff
#

it can actually even go lower and the rule is a .editorconfig applies to any files at its level or lower

leaden ice
#

alright well, I'm not sure 😉

pure cliff
#

so you can even add a second .editorconfig file in say, /Assets/Scripts/Foos and it will "override" all settings for the Foos folder and lower

#

or at least... its supposed to

#

but for me none of my editor configs seem to actually be applying, but resharper and VS show it as loaded and the settings as applied in both of their Preferences menus

#

like if I open my Code Style in Rider, you can see it is indeed "seeing" the .editorconfig file

#

but then its just... not actually applying in the editor itself, its so weird

#

I feel like somehow Unity is at fault here, like its somehow messing with this or something

#

cuz it works fine in a normal dotnet application, it is only an issue for Unity projects O_o

leaden ice
#

could be

#

unity does all kinds of things with the cs project

#

have you double checked that your Rider integration is up to date?

ashen yoke
#

try different package version

#

they are commonly bugged

pure cliff
pure cliff
#

like they both have this same weirdness

ashen yoke
#

probably both packages are bugged

#

¯_(ツ)_/¯

#

im still on a very old vs package because new ones break 2019

#

tried to fix it myself but at some point just decided that fuck it

#

rider one isnt by unity tho right?

gray mural
crystal dagger
#

Hey

#
                headTrans.rotation = Quaternion.Slerp(headTrans.rotation, value2, timeCount * 3.5f);
                if(headTrans.rotation == value2)
                {
                    Debug.Log("PASSEI");
                    secondTime = true;
                    timeCount = 0.0f;
                }
#

For some reason

#

SOMETIMES headTrans is, and sometimes it's not value2

#

Any idea?

leaden ice
#

do not compare with ==

crystal dagger
#

How so?

#

I'm new with this

#

I program in C/C++ but i'm new to unity

leaden ice
#

do something like

if (Quaternion.Angle(value2, headTrans.rotation) < 0.01f)``` for example
leaden ice
#

it's a simple math thing

crystal dagger
#

Yeah, but i'm not familiar with a function i cannot read how it exactly works.

leaden ice
#

If you go some percentage between a and b, you will never reach b

#

ever heard of Zeno's paradox?

crystal dagger
leaden ice
#

Slerp/Lerp are basically functions that say "move x% from a to b"

#

so you will never reach b

#

unless the percentage is 100%

#

the only exception would be that you go so incredibly close you actually got there due to floating point imprecision

river sentinel
#

So I'm trying to make EventArgs work, but now I'm wondering if that's even the right things to do for what I'm trying to achieve. Endgoal: Make it possible to transfer multiple parameters through a UnityEvent in the inspector.

#

Like, I want to pass a string and a bool value, to interact with this: ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class EventChecks
{
public static Dictionary<string, bool> checks;

public static void InitializeChecks()
{
    checks = new Dictionary<string, bool>();
    checks.Add("testCheck", false);
}

public static void SetCheckValue(string checkKey, bool checkVal)
{
    if (checks.ContainsKey(checkKey)) return;
    checks[checkKey] = checkVal;
}

}

leaden ice
#

UnityEvent only supports one parameter

#

you can't change that

river sentinel
leaden ice
#

Simple workaround is something like this:

public string s;
public bool b;

public void DoSomething() { // call this from the UnityEvent
  SetCheckValue(s, b);
}```
river sentinel
leaden ice
#

could be another component, could be the same one

river sentinel
#

I was just wondering if there was a way that I wouldn't need to do that, but if it's the best way ...

leaden ice
#

the point is just delegating the parameters from elsewhere

leaden ice
#

are you setting these parameters statically (in the inspector) or dynamically?

#

e.g. by calling myUnityEvent.Invoke(x, y)

#

if it's the latter you should be able to do it just by declaring your UnityEvent as UnityEvent<string, bool>

#

fi it's statically (in the inspeector) you must do a workaround like I shared

river sentinel
#

I wanted to have a UnityEvent that would call this: public void SetEventCheck(string key, bool value) { EventChecks.checks[key] = value; }

leaden ice
#

yeah that's not what I'm asking though

#

I'm asking how you are sending the parameters into it

#

from the inspector, or from code?

#

like where is the UnityEvent defined and invoked?

river sentinel
leaden ice
#

ok so if you want the inspector you are stuck with the workarounds

river sentinel
#

what's the other methods?

leaden ice
#
public UnityEvent<string, bool> myUnityEvent;

void FireEvent(){
  myUnityEvent.Invoke(someString, someBool);
}```
#

in this case the parameters come from the code somehow

#

of course you could then set someString and someBool separately in the inspector for this component

river sentinel
#

I think I do that for using V3s as spawn coordinates for a warp event. I set up coordinates and call upon the corresponding index for that.

#

It's just likely to get more cluttered if I try to do it with variables ...

#

unless I have events that change the variable index before invoking an event that changes the value ...

#

that way I could do everything without additional components, it'd just be a couple more events each time I want to change a check's value

#

frankly I'd like to work with someone to take a look at the event system I've made so far and just learn if there's a better way to do what I'm trying to do. My current method is just queueing unityevents to fire in sequence ...

karmic zealot
#

My OnMouseEnter code not working in some GameObjects. But it works in copy of the game object I use. Only different is their position.
How can I solve that?

river sentinel
#

@karmic zealot Can I see your code?

karmic zealot
rigid island
karmic zealot
#

Yes

river sentinel
#

what objects does it work on?

karmic zealot
#

They are exactly same

#

only the positions

#

And CSelAreas

river sentinel
#

can we see the GOs in editor?

#

and what exactly is CSelArea#?

karmic zealot
rancid frost
#

How is this posible?

The hex vertices are rendered using the position
the position is the center,

how come to 3 direction arrow is not properly centered on the hex?

karmic zealot
#

I'm trying to select something

river sentinel
karmic zealot
karmic zealot
river sentinel
#

I'm not sure ...

#

I'd ask to call to better see what's happening but I'm not in a situaton where I can atm.

#

what is in the scene? Can we get a view of that?

leaden ice
karmic zealot
#

Or when I change its colliders trigger setting

crystal dagger
#

Thanks sire

rancid frost
river sentinel
leaden ice
rancid frost
#

Mesh are clones of the Hexcell

#

its transform is zero zero

leaden ice
#

is that through a shader? Or what

rancid frost
#

quad

leaden ice
#

quads are rectangular

#

how is it being rendered as a hex

rancid frost
#

vertices

leaden ice
#

?

#

please use complete thoughts!

rancid frost
leaden ice
#

Ok so you're modifying the mesh at runtime in code?

#

this is just an array

rancid frost
#

yes

#

so that is the vertex corner

        public static Vector3 GetPosition(int x, int z)
        {
            Vector3 position;
            position.x = (x + (z * 0.5f) - (z / 2)) * (HexMetrics.innerRadius * 2f) + (x * step);
            position.y = 0f;
            position.z = z * (HexMetrics.outerRadius * 1.5f) + (z * step);

            return position;
        }
#

you pass in coordinates to get spawn location

leaden ice
#

where's the code that modifies the mesh

rancid frost
#

pretty simply nothing complicated

leaden ice
#

wait also before we go down this rabbit hole too far:
Is your tool settings set to "Center" or "Pivot" on the left here

rancid frost
#

wow

#

that fixed the problem 🙂

leaden ice
#

oof

#

it should be on pivot

#

is it on pivot now, or center?

#

if you changed it to center, that's still a problem

rancid frost
#

now its on center

leaden ice
#

yeah it's still a problem

#

your mesh generation code is producing vertices off center

rancid frost
#

hmmm

#

I thought so, but cant be

leaden ice
#

it's not adding any vertices or anything

#

except to this "Vertices" list which seems unused here

rancid frost
#

they are drawn in another method

leaden ice
#

ok so where does "CombineVertices()" come from

#

maybe just show the whole script

#

in a paste site

rancid frost
#
Center position = Position = "(4.33, 0.00, 7.50)"
rancid frost
leaden ice
#

yes I'm sure. Use a paste site

#

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

rancid frost
rancid frost
#

This is from another class, but here is how the hex are spawned

rancid frost
leaden ice
#

you should not be adding Position here

#

because in the mesh, the positions should be in local space

#

not world space

#

The mesh should be positioned by its Transform

#

likewise this way you can share a single Mesh for all of the hexes

rancid frost
#

uhhh

#

ironically, that is what I did before hand

#

the problem however was its very hard to get the position of the surrounded hexes

#

I did eventually figure it out, but another thing was that since my shader relied on the position(notably) the Y position of vertex to color it

#

my shader was always wrong

#

Here is an example

#

if you want to create slopes between the hexes, you will have to spread them out and link them together

#

however since the position are all local, you have to do some trick math to get them

leaden ice
#

I'm not sure about all that but the transform.position is where the gizmo will be

leaden ice
#

whichever you need

rancid frost
#

how?

hidden flicker
#

pretty sure this is a code issue

#

getting these three error messages

leaden ice
#

or uhh float3 worldPos = mul(unity_ObjectToWorld, float4(v.vertex.xyz, 1)).xyz;

dusk apex
hidden flicker
#

unsure what that means

#

also it randomly fixed itself?

dusk apex
hidden flicker
#

...what?

dusk apex
#

You didn't write the lines of code. They're likely not relating to something you've done. It isn't an issue you can fix by coding.

hidden flicker
#

ok

thin hollow
#

I have the following code that adds unique identificators in my objects. But I've stumbled upon a problem: it fires up on a prefab even when I just select it in the browser. Which results in every prefab I place in the scene getting same GUID.
I tried to set field to "0" when I have asset selected in the browser - it just instantly generates new GUID.
While I want prefabs to get unique IDs, but only when I drag them into the editor OR instantiate them in the game, and not when I load level or do anything else (Supposedly this should be prevented by the check that GUID isn't empty before trying to assign it. It is for my save game system, persistent level states and serialization, so I need them to be as static and invariable as they can be).

How can I fix my code?

    public abstract class DynamicObject : MonoBehaviour, ISaveSystem
    {
        [SerializeField]
        internal string objectID;
        internal void OnValidate()
        {
            if (!Application.isPlaying && !EditorSceneManager.IsPreviewSceneObject(this))
                AssignGUID();
            if (PrefabUtility.IsPartOfAnyPrefab(this))
                PrefabUtility.RecordPrefabInstancePropertyModifications(this);
        }        
        /// <summary>
        /// Assign GUID to the object if it doesn't have one already
        /// </summary>
        /// <param name="force">Normally, GUID will be assigned only if the field is empty. This will force new GUID to be created no matter what.</param>
        internal void AssignGUID(bool force = false)
        {
            if (objectID == String.Empty || objectID == "0"|| force)
                objectID = Guid.NewGuid().ToString();
        }
vivid wind
#

Would anyone happen to know of some resources that could help me get started with implementing a system to prevent distance objects from being active and activating them as the player gets close? I'm looking to implement a large Maze game with no area transitions ideally. So I presume I need a system in place to activate entities and other scripts as the player approaches rather than having everything loaded and running.

thin hollow
# vivid wind Would anyone happen to know of some resources that could help me get started wit...

You could do a global game state singleton (if you do not have one already) with a List of game objects, and make it iteratively check distance from player to every object in that list every second of 5 seconds (depending on how fast your player can move and how long straight paths are in your maze), turning them off and on depending on the required distance, and then all objects that should be culled in this fashion add themselves in that game manager list upon Start();

Alternatively you could make that list sit in the player script itself, but this is not a good way to do it.

lucid wigeon
#

Can you even pass around "plain classes" in the inspector? Can they be assigned as a component? That's a fundamental question I came up with. If not, I see not point in using a "plain class"... maybe everything should be a Monobehaviour. Initially I thought "plain classes" are clever to encapsulate data. But it seems they cause more problems than they're worth.

vagrant blade
leaden ice
lucid wigeon
#

To clarify I'm asking about keeping a reference to plain class in the inspector. Otherwise I have to instantiate this plain class separately in each component.

leaden ice
#

if you aren't making a component, you don't make a MonoBehaviour

lucid wigeon
#

But let's say I want to store player health in a class like public class Player{ int playerHealth; } .... when I create new Player() can I pass that around in the inspector somehow? Except by passing around in code.

#

I cannot have 2 components using one instance of this plain class, right?

vivid wind
lucid wigeon
#

Let me prepare another example maybe

#
[Serializable]
public class Player {
    public int playerHealth;
}

public class Component1 : MonoBehaviour {
    public Player player;
}

public class Component2 : MonoBehaviour {
   public Player player;
}
#

If I do this, each component will have its own instance of Player object, right?

#

If I edit values in Component1, then Component2 will have a separate set of values

vagrant blade
#

Yep

vivid wind
lucid wigeon
#

Forgot [serializable]

lucid wigeon
#

So, now, is there any other way to do this, except to turn the plain class into a component, and attach to a Gameobject? Like so:

public class Player: MonoBehaviour {
    public int playerHealth;
}

public class Component1 : MonoBehaviour {
    public Player player;
}

public class Component2 : MonoBehaviour {
   public Player player;
}
#

Now it should be only one instance of Player, right? If assigned using the inspector

vivid wind
# lucid wigeon In that case, yes

So if the class wasn't a MonoBehaviour you'd do something like this for the Constructor public MyClass(IPlayer playerData). However, due to component framework of unity, you can't get access to the constructor to implement this easily. You'd typically want to implement a "Singleton". There are some issues with doing this, as it gives allot of things access to a set of data which is not usually ideal but it is something done to overcome unity's framework without having to use something like Zenject.

#

There are some really good videos that taught me about this, as I've run into this question allot eairly on.

#

I'll grab some links.

#

https://www.youtube.com/watch?v=mpM0C6quQjs implementation and good overview here.

Sign up for the Level 2 Game Dev Newsletter: http://eepurl.com/gGb8eP

The Singleton Pattern is a design pattern that's well-loved by Unity game developers. But, unfortunately, it has some serious drawbacks that most programmers don't discover until it's too late. In this video, I'll show you what those drawbacks are so you can avoid them in the...

▶ Play video
#

Basicly you have like a GameObject called "GameManager", game manager contains a component monobehaviour containing the data you want to access. You write some code into the awake function that ensures that when the class is instantiated, it is the only one and sets itself to a public static on the class itself (Component1.Instance). Then you can access that data via that reference i.e Component1.Instance.Player.GetHealth() or something like that.

lucid wigeon
vivid wind
# lucid wigeon Thanks. Although 80% of this video says not to use singletons xD

singletons are kind of a flashpoint for developers, I think because the idea of making something publicly available anywhere is not considered good code professionally. However, for smaller, idie games it should be acceptable so long as you are aware of the drawbacks and concerns. https://youtu.be/iQvCGHPomr0 goes more indepth why it could be ok to use Singeltons.

The first 1000 people to use the link will get a free trial of Skillshare Premium Membership: https://skl.sh/jasonweimann03211

Are singletons really that bad? Let's discuss why they might be somewhat helpful in your unity3d game, what some of the issue can be, and how you can apply the singleton pattern in your games.

Check out the Course: htt...

▶ Play video
lean sail
#

its something you should just use if theres only ever supposed to be one. Like a save system is a good example, you dont need 2 different scripts saving to your one pc. Another example i use in my game is a checkpoint system, each level only has 1 list of checkpoints but thats per design

hidden flicker
#

why do gameobjects move when they're inactive?

lean sail
#

is this gameobject perhaps a child of another moving gameobject

dusk apex
hidden flicker
lean sail
#

then you'll have to show your code, because you are leaving a lot of detail out

dusk apex
#

You're going to have to show us what you mean because that likely isn't the case

lean sail
#

i can guarantee that if i open a new project, put a cube in the scene, toggle it inactive/active, it wont have moved

#

if it does then ill need an exorcism, which isnt a code issue

hidden flicker
#

inactive position

#

active

lean sail
hidden flicker
#

suddenly it fucking moves

#

also, in the editor, the rifle appears here. right in front of the camera

#

when you PLAY, it moves

#

and only the mesh moves! not the arms! which are both children of the same gameobject!

lean sail
#

i really dont get why you're sending screenshots, all i asked for was code. The first 2 images literally show that your object's local position doesnt move

#

meaning that your parent is moving

hidden flicker
#

very new to unity, don't know what info to provide :)

lucid wigeon
#

Do you rather have separate action for each event type or have enum for that?
A)

public delegate void EntityClickedAction();
public event EntityClickedAction OnPlayerClicked, OnBuilderClicked, OnEnemyClicked, OnAnimalClicked;

or
B)

enum EntityType { Player, Builder, Enemy, Animal }
public delegate void EntityClickedAction(EntityType type);
public event EntityClickedAction OnEntityClicked;

Personally for me the giant drawback for B) is that you need a giant switch statement to handle that. And in A) you can have neat little methods with handlers for each type.

hidden flicker
#

figured it out. accidentally added an animator to the mesh

lean sail
# lucid wigeon Do you rather have separate action for each event type or have enum for that? A)...

well these are delegates, not actions. Id say it depends though on what you want. Do subscribers care about if a "Player, Builder, Enemy, and Animal" are all clicked? Do they only care about one or a smaller subset?
It can be fine to have a lot of events, I would just look at adding your own custom add/remove function because I believe every event would be allocating for every instance of this class. Instead you could just have it allocate when something actually cares to subscribe to it since a lot of events often go unused

low cave
#

Is there a way to make a public variable be of type ParentClass, and assign ChildClass (inherits from ParentClass) to it?

lean sail
low cave
#

is there a way to do that from the editor with public variable?

#

dragging ChildClass to a ParentClass variable doesn't work

#

@lean sail

lean sail
#

because you havent shown much about your project

spring creek
low cave
#

I have an Attack class and a Player that needs to reference an Attack, and the different attacks inherit from Attack. I need to reference that inheriting class for the attack.

lean sail
#

no, like a c# interface

spring creek
swift falcon
#

am i wrong to hate the inspector for connecting up objects? I feel that it creates an unsearcbable coupling.

lean sail
low cave
#

I'm trying to drag a c# script that inherits from Attack from the Project window into here

swift falcon
#

maybe i can search the inspector for the couling? code makes it clear to me and is search able

#

so if i where to say that all couling should happen using code in the future if at all possible, that wouldn't be too strange, right?

lean sail
swift falcon
#

i see

#

that is a good point that i didnt of.

#

so there is a case where using the inspector isn't worse

#

good to know. thank you

#

so outside that case i would be well served with my ruling?\

lean sail
low cave
#

I'm trying to drag StaticAttack into Main Attack from the bottom Project window

#

It's not in the scene

#

Well the player with the main attack isa

#

but not the StaticAttack script

lean sail
# swift falcon so outside that case i would be well served with my ruling?\

you can do whatever you'd like, but sometimes using the inspector is just easier. If its a difference of GetComponent<> in awake vs dragging it in the inspector, no ones gonna really fight you on that.
And also for level design, some things really are just easier to drag in the inspector. Like if you have a button that opens a very specific door, and lots of these button -> effect things, then it'll be hard to set this up through code when something like unity events already exist.

lean sail
swift falcon
#

but there is no way to search the inspector for the links, i just have to remember them?

spring creek
lean sail
#

the inspector shows you the links

swift falcon
#

but if i have a ton of object how do i find something someone else did in the inspector and didnt document?

lean sail
#

if your system is complex to the point that you're going through 50 gameobjects linked together, you probably need to change something

low cave
swift falcon
#

i hate that i can have an object selected and i cant find where it's been inserted into the other obejcts

#

unless i can and i dont know how?

lean sail
low cave
#

thanks for the help

lean sail
swift falcon
lean sail
#

exactly where i said itd be, you right click a component and press Find references in scene

#

doubt you'll really find much use in this though, if you dont know what an objects purpose in the scene is

swift falcon
#

i dont see it

lean sail
#

That's cause it's not a component

#

I mean the things like 'transform'

swift falcon
#

so i can't see where it's been dragged into something

lean sail
#

For the actual gameobject im not sure. For the components of an object, you can

swift falcon
#

right

#

thank you for your help

#

as a noob to unity this would be a great feature

#

as is i tear my hair out

dusk apex
#

You should probably not ever be referencing the game object as type GameObject but instead as the specific component type. Unless you're simply changing the activeness or name...

swift falcon
#

@dusk apex i wish i understood what you meant

#

it sounds like you are saying dragging game object into components willy nilly is a bad idea

#

which is my thesis

dusk apex
swift falcon
#

hmm, still not following

#

sorry

#

what i am trying to do is make my code/project more understandable and searchable for all the coupling that exists because the coupling seems a lightmare now in my project

dusk apex
#

Reference the game object as the specific component type

rain minnow
dusk apex
rain minnow
dusk apex
#

Then you'll be able to find references of the component etc

spring creek
#

I'm not sure why you guys think they are referencing gameobjects instead of, say, text? Did I miss an inspector photo?

They have like 30 text objects in the scene and don't know where each one is referenced. That would be the same issue if they did public gameobject or public text

Which is an architecture/organization problem hahaha

swift falcon
#

i cant search the ui if do it as far as i can can tell

dusk apex
#

They were saying find reference using the inspector wasn't applicable because they would like to search using the Game Object in scene. I'm sure either they're misunderstanding how component reference works or are simply referencing Game Objects, which they should not be.

swift falcon
#

there is something sublte going on here that i am not following i think

rain minnow
swift falcon
#

as is i dont like changing the scene if i can do it in code because then its search able and i dont have to worry avbout merging the .unity files

dusk apex
#

If you type public Button play in code and drag the button object into the inspector field. You're referencing the Button component and it can be searched for via component using what was previously suggested.

swift falcon
#

that is where i am, but it seems there is a higher plane of existance i am missing out on

spring creek
#

Which would be the same problem no matter what type the field is.

Does that make sense?

swift falcon
spring creek
spring creek
#

Which is a perfect solution to what you want, just reversed

swift falcon
#

i think i need a screen shot. sorry

#

ok

#

let me try

spring creek
#

To explain a little more clearly, I assume you have text fields in foreground maybe? Select that in the hierarchy (on the left). Right click that field (the box you drag things into) in the INSPECTOR (the one on the right) and click find. It will show you which object the field is referencing (regardless of the type of the field)

swift falcon
#

i see.

#

i hope this will help me going forward. thank you all for your kind help.

atomic sinew
fervent jacinth
#

how does the smooth variable work in lerp functions? i never really understood it

lean sail
atomic sinew
lean sail
atomic sinew
atomic sinew
wintry crescent
#

Hi, I have an UnityEvent, and I want to call a function
public void MyFunction(MyEnum enum) but I don't seem to be able to select it in the inspector. Can you not call functions with enum parameters with a generic UnityEvent?

lean sail
wintry crescent
#

I could do UnityEvent<MyEnum> but that doesn't let me select the value of said enum in the inspector, which is what I need.

#

I have set MyEnum to Serializable

lean sail
#

Otherwise I'd just suggest running through the debugger

#

You'll see all the values that way

dusk apex
#

What I'm referring to.

spring creek
atomic sinew
spring creek
#

So I just read between the lines

#

Lets not muddy up the channel though. He's gone, and it doesn't really matter anymore unless they come back

dusk apex
# spring creek https://discord.com/channels/489222168727519232/763495187787677697/1133891483393...

He simply misunderstood what was advised.
I believe that actually finding the objects that are referencing the instance is what what's wanted and that by searching via component, it will work.
Thus why I brought up how is not likely or wanted to reference something as type GameObject (unless you're really wanting no other feature) and that searching via inspector-component would be perfectly suitable.

spring creek
#

But w/e. Again, it's not relevant anymore. Have a good one

silk cairn
#

whoops not code

vivid wind
# thin hollow Bump

Can you overload the instantiate call to create and set a new guid for the new object?

lean sail
vivid wind
spring creek
#

Never used that though, so i dunno

vivid wind
rain minnow
wintry crescent
thin hollow
rain minnow
wintry crescent
# rain minnow because it's not a primitive type: int, float, string, bool, etc. . . .

I assume UnityEvent is using reflection, to get the functions and arguments, when selecting what to call. It is 100% possible to tell apart an enum field from an int or a string field, in the function parameters, with reflection. They need to create an input field in the inspector for that particular parameter anyway. Different one for a string, different for an int, different for bool. Then why didn't they add an enum one as well? That's just such a missed opportunity.

wintry crescent
next pawn
#

Looking for help with A* Pathfinding

quartz folio
# wintry crescent

I presume they haven't done it because an enum can be any type of integral type and they don't want to add some more logic to figure out what needs to be serialized, but I agree it can be done and probably should be done, at least for enums that use int as their backing type.

rain minnow
# wintry crescent also. int, float etc. all derive from ValueType, which derives from Object, the ...

enum is not a primitive type (data types built into the language) as any "custom" enum we create must derive from enum. we do not derive from int, float, string, bool, etc., to create our own variables. yes, it's a value type, but that does not denote it a primitive type. a struct is also a value type but it's not a primitive type. an anum can have flags, be used as bits and represent multiple integral types

as you can see under the hood, the PersistentListernerMode selects the type of primitive to use for the argument, then Arguments assigns the value as it only consists of the primitive types that can be used within the inspector for events . . .

spring creek
unique cloak
#

Hey guys I have this code which is basically to iterate through a dictionary of items with a decrementing timer as the value property in the dictionary. When the timer hits 0, I want to remove the kvp from the dictionary, but I cant modify a dictionary while enumerating through it so I add the values to a list which I then remove and clear afterward.

    public void DigestiveSystem()
    {
        foreach (KeyValuePair<PlantBehaviour, float> plant_kvp in plants_consumed)
        {
            plants_consumed[plant_kvp.Key] -= Time.deltaTime * ecosystemScriptableObject.tickspeed;
            if (plants_consumed[plant_kvp.Key] <= 0)
            {
                to_be_removed_plants_consumed.Add(plant_kvp.Key);
            }
        }
        RemovePlantsFromDict();
    }
       
    public void RemovePlantsFromDict()
    {
        foreach (PlantBehaviour plant in to_be_removed_plants_consumed)
        {
            if (plants_consumed.ContainsKey(plant)) {
                plants_consumed.Remove(plant);
                Destroy(plant.gameObject);
            }
        }
        to_be_removed_plants_consumed.Clear();
    }

For some reason, this is still telling me I'm trying to modify the dict while enumerating through it, i.e. InvalidOperationException: Collection was modified; enumeration operation may not execute. Any ideas as to how I could correct this?

rain minnow
quartz folio
#
foreach (KeyValuePair<PlantBehaviour, float> plant_kvp in plants_consumed)
        {
            plants_consumed[plant_kvp.Key] -= Time.deltaTime * ecosystemScriptableObject.tickspeed;

You are writing to the collection during a foreach, you can't do that

spring creek
halcyon venture
#
    void HitTarget(Vector3 pos)
    {
        audioSource.pitch = 1;
        audioSource.PlayOneShot(hitSound);

        GameObject GO = Instantiate(hitEffect, pos, Quaternion.identity);
        Destroy(GO, 5);
    }
``` uh my audio isnt playing. anyone know why? this function is 100% being called by the way.
#

and my computer speakers are fine

#

and its assigned

unique cloak
#

Thanks gentlemen, appreciate the extra set of eyes

quartz folio
halcyon venture
halcyon venture
#

may bayt

#

by bad

rain minnow
quartz folio
#

Glad to help 🙂

rain minnow
halcyon venture
#

ye.

copper blaze
#

i'm trying to use unity events to communicate game logic to my ui using events, is it okay to fire an event every frame (in the update method) or is it bad for performance?

wispy wolf
#

Its two foreach loops, which isn't ideal if this is going to happen a lot (like multiple times per frame)

unique cloak
# wispy wolf https://dotnetfiddle.net/dQNw7U This works

This is what I wrote

    public void DigestiveSystem()
    {
        // Loop through main and reduce timers on alt
        foreach (PlantBehaviour k in plants_consumed_main.Keys)
        {
            plants_consumed_alt[k] -= Time.deltaTime * ecosystemScriptableObject.tickspeed;
        }

        // Loop through alt and reduce timers on main
        foreach (PlantBehaviour k in plants_consumed_alt.Keys)
        {
            plants_consumed_main[k] -= Time.deltaTime * ecosystemScriptableObject.tickspeed;
        }

        // Loop through main and if timers are <= 0, remove values on alt
        foreach (PlantBehaviour k in plants_consumed_main.Keys)
        {
            if (plants_consumed_main[k] <= 0)
            {
                plants_consumed_alt.Remove(k);
                Destroy(k);
            }
        }

        // Alt is now the correctly updated dict
        // Set main to alt
        plants_consumed_main = plants_consumed_alt;
    }

But its still throwing the error saying I'm trying to modify dict while enumerating through it

rain minnow
unique cloak
#

I just used two dicts main and alt

#

which both have all the values in them

spring creek
soft shard
rain minnow
#

but it's not uncommon. input is used in a similar way . . .

copper blaze
#

what if i want to display the remaining time on the timer?

soft shard
# copper blaze updating a cooldown timer

Another way you can handle a timer is with Time.time, which will tell you the time in seconds, since the scene loaded, you could instead use that to know when your event started, pass the length the timer should run for, and know when it ends by subtracting Time.time from the event time value

rain minnow
analog relic
#

Anyone know if there's a way to make Texture2D CPU-only? (so that it doesn't take up any memory on the GPU. Or is it that way by default? A little confused)

copper blaze
rain minnow
# unique cloak Good call thanks sport

that's what i use for my custom timer. i had a tuple of <timer, Action> but ended up adding Action to the timer class itself, though i could have created a class to hold them both as fields . . .

wispy wolf
unique cloak
rain minnow
# unique cloak Gotcha thanks, was wondering how to do this, it's alright I'm gonna go back and ...

oh, forgot to give an example. here is one using a list of tuples . . .

public class EcosystemScriptableObject : ScriptableObject
{
    [SerializeField]
    private float _tickSpeed = 0;
    
    public float TickSpeed => _tickSpeed;
}

// Some class.
[SerializeField]
private EcosystemScriptableObject _ecosystem;
private List<Tuple<PlantBehaviour, float>> _plantsConsumed = new();

void DigestiveSystem()
{
    var (plant, timer) = default(Tuple<PlantBehaviour, float>);
    var  count = _plantsConsumed.Count;
    for (var i = count - 1; i >= 0; --i)
    {
        (plant, timer) = _plantsConsumed[i];
        timer -= _ecosystem.TickSpeed;

        if (timer <= 0)
        {
            _plantsConsumed.RemoveAt(i);
        }
    }
}
unique cloak
#

Thanks

gray mural
#

anyway, you cannot selialize it

#

if you want, you have to create a struct

craggy veldt
edgy ether
#

ok so i have a question about using "new" within my Update() methods inside a script.

if i use "new" under Update(), does that mean it will keep creating a whole new variable every update frame? it's not reusing the first one it made?

i'm asking because im trying to actively think about ways to optimize my code

craggy veldt
#

yes it will create the new instance of it every frame

ashen yoke
#

you need to understand the difference between variable and object

#

variable itself is allocated on the stack, in the method scope, once execution leaves the method the variable is gone

edgy ether
#

ah

ashen yoke
#

but the object the variable points to is not, it stays in the heap memory waiting to be garbage collected

#

and by calling new on classes you allocate a new object

#

which then the variable points to

quartz folio
#

though that depends whether it's a class or a struct, and where the struct might be declared/stored

ashen yoke
#

doesnt happen with structs, they are also allocated on the stack

craggy veldt
#

struckt can also be (accidentally)allocated on the heap e,g defensive copy

ashen yoke
#

in general doing new Vector2 is ok, no garbage generated, doing new MyClass() will allocate an object on the heap each time, piling them up until gc

edgy ether
#

aaah!

#

alrighty then, imma go ahead and take that off of update then. although the terminology for class and struct is still blurry for me, it might be better if i just manage it at start

#

thank you very much for the info. i've always just been looking and seeing what things did, but i never had a full idea of what happens under the hood when i put it to practice 😅

ashen yoke
#

if you want to unblur it you need to understand the difference between heap and stack memory

#

they are not different physically, but how it is treated/cleared

#

structs are designed to utilize the stack mechanics, so they have properties that stem from that, objects are designed to be stored in the heap

#

there is much more to it, but this is the key factor in why they behave so differently, and why structs dont cause heap allocations and why they are passed by value

edgy ether
#

ah ok, well im going to google this up and read up on it more. thank you guys for the information 🙇🏾‍♂️

#

it'll be good to get a better understanding of how it works behind the scenes ^^

lean sail
#

best way in terms of what? its like 2 lines of code

#

have some central code that reads/writes your json so you dont have different scripts (all implementing the same logic) trying to do this at the same time

#

🤷‍♂️ ive never used TextAsset, i just get the file with system io

mellow sigil
#

TextAsset is by far the easiest method if you don't need to write to the file

halcyon pelican
#

So, I have a problem I need solving. I have an animation of a little mining guy hitting a rock

Each time he hits the rock, I want him to slowly reveal a rune that is only active when he clicks on the little miner 4 times. When it reveals the rune, clicking on the little miner character shouldn't do anything else. I was thinking that I have some kind of variable that slowly clicks up to 4 times starting at zero, at which point it can be captured for magical power.

How do I do that with a separate code from what I have here? At this point, this code works perfectly well for what it does and I don't want to add to it because it already has so many other animations linked to it.

I feel like I"m going insane!

cosmic rain
lucid wigeon
halcyon pelican
#

And since it only links to th3 animation of the miner, i was thinking i of just doing a variable increase thing

#

Where each increase just changes the sprite of the rock

#

This is a visual novel so dont worry about other rocks that need to be affected or something

#

There's only the one rock that gets mined to reveal the rune

lean sail
# lucid wigeon Not sure what you mean about unused events? Can't you just remove it if it's not...

if you have many instances of an object, its possible not every event will be subscribed to. Think of a button, you can have 100 buttons on screen and theres a lot of events associated with each one (like onclick, hover enter, hover exit etc etc i dont actually remember more names)
So if you're just subscribing to the on click method, a lot of events are unused but they exist because someone might wanna use them

cosmic rain
halcyon pelican
cosmic rain
#

Isn't that what you want though? To animate the miner and nothing else? Then what's the problem?
That message only makes me more confused.
You should really restart your explanation and maybe attach some video/screenshots making it clearer if you have trouble explaining in words.

halcyon pelican
cosmic rain
halcyon pelican
#

Hmm

#

Is it possible to make the reference a new script or do i have to add it to the miner's script?

cosmic rain
#

Wdym by "making the reference a new script". That sentence doesn't make any sense.😣

lucid wigeon
#

Anyway, how much cpu and memory could be used to be subscribed to a couple of events? batman_hmm

lean sail
lean sail
cosmic rain
halcyon pelican
#

Cause as said before, the script on the miner is one used in other objects but i can just make a seperate version for the miner if it needs to be in the same script

timid badger
#

hey guys, so im newbie in photon and i have a problem that when i play w/ two players the players swap the controls idk what is the problem can anyone fix that?

using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;

public class FirstPersonMovement : MonoBehaviour
{
    public float speed = 5;

    [Header("Running")]
    public bool canRun = true;
    public bool IsRunning { get; private set; }
    public float runSpeed = 9;
    public KeyCode runningKey = KeyCode.LeftShift;

    Rigidbody rigidbody;

    PhotonView view;
    /// <summary> Functions to override movement speed. Will use the last added override. </summary>
    public List<System.Func<float>> speedOverrides = new List<System.Func<float>>();


  
    void Awake()
    {
        // Get the rigidbody on this.
        rigidbody = GetComponent<Rigidbody>();
        view = GetComponent<PhotonView>();
    }

    void Update()
    {
        if(view.IsMine)
        {
            
            // Update IsRunning from input.
         IsRunning = canRun && Input.GetKey(runningKey);

         // Get targetMovingSpeed.
         float targetMovingSpeed = IsRunning ? runSpeed : speed;
            if (speedOverrides.Count > 0)
            {
             targetMovingSpeed = speedOverrides[speedOverrides.Count - 1]();
             }

         // Get targetVelocity from input.
            Vector2 targetVelocity =new Vector2( Input.GetAxis("Horizontal") * targetMovingSpeed, Input.GetAxis("Vertical") * targetMovingSpeed);

         // Apply movement.
         rigidbody.velocity = transform.rotation * new Vector3(targetVelocity.x, rigidbody.velocity.y, targetVelocity.y);
        }
    }
}
halcyon pelican
#

Where do i even put the the reference linking to the rock.

cosmic rain
rancid frost
unique cloak
#
    [System.Serializable]
    public class Class_A
    {
        //fields here
    }

    [System.Serializable]
    public class Class_B 
    {
       //fields here
    }

    [System.Serializable]
    public class Class_AB
    {
        public List<Class_A> class_a;
        public List<Class_B> class_b;

        public Class_AB()
        {
            class_a = new List<Class_A>();
            class_b = new List<Class_B>();
        }
    }

    Class_AB class_ab = new Class_AB();

Why can I not see class_ab in the inspector? this is inside a scriptable object

cosmic rain
unique cloak
#

Class_AB class_ab = new Class_AB();

#

the bottom line?

tired elk
#

because you didn't specify it as public

cosmic rain
tired elk
#

by default fields are private and are not exposed

void remnant
#

Hello, when I run the code bellow, an error pops up:
NullReferenceException: Do not create your own module instances, get them from a ParticleSystem instance
UnityEngine.ParticleSystem+MainModule.set_startSize (UnityEngine.ParticleSystem+MinMaxCurve value)

        var hit = Physics2D.Raycast(transform.position, transform.right, range);

        var main = Emmitter.main;
        if(hit.collider != null)
        {
            main.startSize = hit.distance;
            transform.localPosition = hit.distance * 0.5f * Vector2.right;
        }
        else
        {
            main.startSize = range;
            transform.localPosition = range * 0.5f * Vector2.right;

        }
#

In the documentation it says that yuo have to do this it this way (by storing ParticleSystem.main in a variable)

#

Why does the error appear and how do I fix it?

cosmic rain
void remnant
#

In the documentation it says that it's not a normal struct

#

it's something different and I don't need to reasign it

#

a sort of interface

#

HEre's the line where the bug happens:

 main.startSize = range;
#

if I do it this way, it doesn't compile as Emitter.main is not a variable

Emitter.main.startSize = range;
#

I also tried

main.startSize = new ParticleSystem.MinMaxCurve(range);
#

still doesn't work

#

Here's a piece of code in a different script that works

        var mainSystem = Emitter.main;
        mainSystem.startSpeed = speed;
        mainSystem.gravityModifier = gravityIntensity;

        Emitter.Emit(1);

How can this work and the previous one not?

leaden ice
void remnant
#

Wait! I think I'm on to something... When I place the Gamobject with this script attached before I start the game, everything works just fine. But when I instantiate it at runtime, something breakes

leaden ice
#

What is Emitter referring to

#

Is it a prefab, or is it the instance in the scene

#

If it's the prefab that'd be why

void remnant
#

a prefab

leaden ice
#

Well yeah

#

That makes sense then

void remnant
#

wait how

leaden ice
#

Poor error message but, you're trying to mess with a particle system that isn't really initialized

#

It doesn't exist in the world

#

It's just a prefab

void remnant
#

one sec

leaden ice
#

Calling Emit on a prefab is similarly wild

rancid frost
#

How is this possible?

#

My array is returning all zeroes, but the static variables are set

void remnant
#

but I instantiate the prefab


//gun script
if (GetComponentInChildren<BulletT>(true) == null)
            Instantiate(bullet, transform.Find("ShootingSpot"));
//bellow is the bullet script
    void Awake()
    {
        Emitter = GetComponent<ParticleSystem>();
        Debug.Log(Emitter);
    }
leaden ice
rancid frost
#

Would creating a variable reset the static onces?

leaden ice
#

Not really sure what you mean by that tbh

rancid frost
#

where is it being reset?

void remnant
#

oh wait, I think I know what happened. Thanks @leaden ice

rancid frost
#

could it be that the static array is initialized before the static variables are?

prime sinew
rancid frost
lucid wigeon
prime sinew
#

what are you trying to reset?

rancid frost
#

Im creating a mesh using a group of hex

I created static variables to hold the hex sizes...which are uniform for all hexes

prime sinew
#

first things first, doing HexTile hex; like that has nothing to do with static variables. That's just creating a local variable of type HexTile

rancid frost
#

just static

ashen yoke
#

how does it compile even then

prime sinew
#

so what are you trying to reset?

rancid frost
#

im initiating static variables from another class

#

but the array for some reason is not updated

ashen yoke
#

TIL there are no limitations on static fields in initializer

#

which is very bad and you shouldnt do it

#

because exactly of your issue the order of init is undefined

rancid frost
#

so the array is getting init before the variables are then?

ashen yoke
#

right now yes

#

on next launch maybe not

#

undefined

tired elk
ashen yoke
#

@rancid frost instead of that just use InitializeOnLoadMethod or RuntimeInitializeOnLoadMethod

#

if you need the statics

#

actually not "or" but both for it to work correctly in editor as well, if you need it at edit time

rancid frost
#

ok, will do

ashen yoke
#

also where do you set the fields?

#

i dont see it

#

they are all 0

#

oh

#

no that would never work, the initialization happens when static contructor is invoked

#

so it will happen before you assign any values externally to those fields

#

thus they are zero

rancid frost
#

ok

rancid frost
ashen yoke
#

you dont use it on array

#
static class Util
{
    public int[] array;

    [RuntimeInitializeOnLoadMethod]
    static void Init()
    {
        array = ...
    }
}
#

this at least will ensure that the static constructor is called before everything else

#

not the first time you access static members of that class

#

plus not everything is allowed to be called from ctor, so this is a safe init point

rancid frost
#

ok

#

Is there a way to edit these values from editor?

I know static variables cant be edited from editor, I thought perhaps making it a singleton

ashen yoke
#

instead of that you should use a scriptable object

#

which you can then make a singleton if you need

#

so access would be something like

#
HexSettings.instance.stepDistance;
uneven monolith
#

Yeah scriptable objects as static variable holders are rly powerfull

tired elk
#

Having it as a singleton doesn't make much sense tho'

uneven monolith
#

I mean yeah u can just make it serializeable reference, or find it with resources folder find

#

Anyway the strength of SO is that u dont have to make new instance/object for it in every scene like you would with monobehaviour singleton

uneven monolith
#

No

#

SO= Scriptable Object

#

ignore my brain lagging

#

But scritpable object can be singleton or not, doesnt rly matter that much, i think singleton is unnecessary, because it only saves the hustle of adding it to every object where u need it in inspector(which i myself avoid with custom attribute fields and other fancy stuff, but lets not go deeper onto that)

rancid frost
#

I see

#

so, if I am sure Im only gonna use it once and wont modify, I should go with SO

ashen yoke
#

no

tired elk
#

It's not that

ashen yoke
#

SO is simply a serialized class

#

data object, for configs, definitions etc

#

it is treated as just another asset on disk in the project that you can edit with inspector

tired elk
#

See it as a prefab that just holds your variables

rancid frost
#

ok

lucid wigeon
#

can you create SO simpler than adding definition and menu annotation and click menu -> scriptable object -> create my scriptable object?

tired elk
#

Depends on the use case, but you can instantiate it as you would with a prefab

lucid wigeon
tired elk
#

At runtime, it's not necessarily interesting

tired elk
#

But, imagine you have an item editor to create fancy swords, shields, and so on, it is useful

lucid wigeon
#

so that's to generate and save SO dynamically I understand

#

instead of clicking create and filling out SO properties manually

lucid wigeon
#

Do you try to write your scripts so that anything that is possible will work in the editor? E.g. for generating terrain you don't need a game instance and just a custom editor with "Re-generate" button. So that you can fiddle with that instead of hitting "Play" all the time. Is that good or a waste of time?

rain minnow
trim schooner
ashen yoke
#

you just need to weigh cost/benefits

lucid wigeon
#

Ok, thanks

simple ridge
#

Hi everyone, I was wondering if there was a way to do a Physics.CheckSphere, but only for a specific collider?
I know I could just do OverlapSphere and then loop through checking if that sphere was in the list, but that seems inefficient to me given I only want to test against 1 collider rather then many. Is this possible?

primal wind
#

Use a layer or tag

#

A tag would be better

tired elk
#

You can put the specific collider on a special layer and make your CheckSphere use a layermask

simple ridge
#

It would be a bit hard to do this given I'm using tags and layers for these spheres already for something else. Is there a way to do this without layers and tags?

#

colliders* not sphers sorry

quaint rock
#

you could use methods from the collider its self

fervent furnace
#

Create a script or put some variable on the script that can help you distinguish different gameobjects

quaint rock
#

colliders have there own ClosestPoint and Raycast methods

#

that only act on said collider

simple ridge
#

Does the collider have (is contained within sphere) type methods? I'll look into that. thanks

quaint rock
#

what type of collider is it?

#

also you could just say screw it, and do a regular sphere check, and just filter the results based on a component

ashen yoke
#

2d/3d?

#

for 3d

primal wind
#

I had no idea that was a thing

#

That could be useful in the future

tired elk
#

But I think it doesn't really answer their problem. I think their idea was to ignore all but a specific collider. ComputePenetration would still require to loop through colliders which entered the overlap sphere (from what the example show I mean)

quaint rock
#

either see if you can do what you want based on the per collider methods

#

or jsut filter out the results

ashen yoke
#

i dont understand, if you already know the specific collider why loop?

quaint rock
#

either by holding reference to the good colliders and comparing

#

or checking for a component

simple ridge
# quaint rock also you could just say screw it, and do a regular sphere check, and just filter...

Its meant to be a 3D pickup interactable system for VR, so interactable items sit on a interactable layer (then get shifted to a different layer so they don't interact with the hands for a few frames after release). I'm working on expanding this to two hands to allow for the second hand to look like its changing its anaimation if its attempting interaction and is within range of the given collider. This is more or less done now but right now I'm using a distance check. I want to make this more robust and have it be that if the collider that invokes the interaction is still colliding during a "holding phase" then change animation, rather then just doing it arbitaruly with a distance check (as there could be much larger or smaller objects)

quaint rock
simple ridge
simple ridge
quaint rock
#

regular OverlapSphere, then you check the results contains the collider you care about

tired elk
simple ridge
#
Collider[] result = UnityEngine.Physics.OverlapSphere(_transform.position + _transform.rotation * _sphereCollisionTestOffset, _sphereCollisionTestRadius, _interactionlayerMask);
return result.Any(resultsCollider => collider.GetInstanceID() == resultsCollider.GetInstanceID());

This is what I think I'll go with for now, just filter the results and see if the spehre I care about is in there. But I am intrested to see if there are better ways of doing this though

quaint rock
#

since there is already a interactable layer, you are not going to need to loop that much

#

though i would use the NonAlloc version

#

why use instanceid

#

you can just compare the colliders directly

simple ridge
#

Good point xD

quaint rock
#

they are reference types and will compare by pointer

simple ridge
#

Removed the instance ID part now

ashen yoke
#

confused me, initially it was a specific collider test, turned out to be actually finding a specific collider

quaint rock
#

well its a certain collider he just wants to know if its in a certain radius

tired elk
#

Why use physics if it's just a distance test ?

quaint rock
#

also, if its 1 collider and 1 raidus to check

#

distance is enough

#

though guess he wants to account of the size of the collider

tired elk
#

If it's a primitive collider, you can access its size and adjust your distance formula without using Physics. It would cost less.

quaint rock
#

thats assuming its not a mesh or a compound collider

tired elk
#

But, I don't know their exact use case, so I'll assume they know what they want

quaint rock
#

also 1 physics call is not worth opmtizing

#

like not at all,

simple ridge
#

I assume distance check would need to use the closet point on a sphere. Which I can get with the collider, but what would happen with the point is inside the collider?

quaint rock
#

have done plenty of games with hundreds of raycasts per frame, and perf is fine

#

would just make it work in the way you best understand and move on to other things to solve

tired elk
simple ridge
#

Yeah probs for the best, I'm jsut just obessing over the performance

quaint rock
tired elk
#

And I agree with this statement lmao

quaint rock
#

perf you learn with experience what to worry about. but generally make it right and easy to understand and only if there is a issue profile and learn why

#

10 or 12 years ago, i am sure i used to obess over small things like that too, just kinda comes with learning

simple ridge
#

Yeah xD

#

Thanks btw for helping out!

glad briar
#

Hi everyone, I came here with a question, I actually try to make some UnitTest on my unityGame et learn about Assembly, I create a Assembly for test and my principal application and I wanted to create another assembly for my Object models, but I have a problem, in my assembly I linked the Application assembly (the main prog) and the Entities assembly, in my application, nothing change it’s work good, but, I wanted to move my player script in a model and I use some script in my main assembly.
So the question is: did I have a possibility to use some script from the main (if I link the Application assembly to the Entities assembly he gonna make a loop so a new error) or I need to recreate my player object?

rancid frost
glad briar
#

i did this

#

but if I do this in my entities and link the main project ( Application) I get a error because I create a loop

#

I don't know if this gonna help but i create a schema of my problem

lament river
#

Any idea why invoking UnityEvent doesn't play particle effect? It does invoke other methods correctly and the particle system plays correctly if I press the editor's Play button

swift falcon
#

I doubt this is possible to do in any easy way but...

Can I somehow get the material ID of where my raycast hits?

vast current
#

idk if this is the right channel for this but I want to make real-time voxel models in my game, so i have instantiated some gameobjects for the general shape of the voxel and i want to 'scan' over these game objects and generate a mesh which converts them to voxel, does anybody know how i can do this?

steady moat
#

There is multiple one out there

vast current
steady moat
#

sharedMaterial*

vast current
swift falcon
#

Yeh but there are multiple materials, so it's getting the correct one

steady moat
#

You can get all material of a given mesh

swift falcon
#

But I guess I'm going to have to just have colliders for different material ID segments and pull an ID from that... Not how I'd like to do it but I think that's the only way?

swift falcon
#

Hmm that might be the way, thanks

#

I'll have a look

#

I see so the Submesh is rendered seperately because of the shader on it, so that'd be my material ID

vernal bridge
fervent furnace
#

so what happens?

swift falcon
#

It gets locked in an animation

#

The animator states might not be set right so it's not exiting out of that run animation

Or your code isn't updating it right

vernal bridge
vernal bridge
#

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

public class PlayerMovement : MonoBehaviour
{
    private Rigidbody2D rb;
    private Animator anim;
    private SpriteRenderer sprite;
    private float dirX = 0;
    
    // Start is called before the first frame update
    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        sprite = GetComponent<SpriteRenderer>();
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    private void Update()
    {
        dirX = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(dirX * 8f, rb.velocity.y);

        UpdateAnimationUpdate();
    }
    

    private void UpdateAnimationUpdate()
    {
        if (Input.GetButtonDown("Jump"))
        {
            rb.velocity = new Vector2(0, 14);
        }
        if (dirX > 0f)
        {
            anim.SetBool("running", true);

        }
        else if (dirX < 0f)
        {
            anim.SetBool("running", true);
            sprite.flipX = true;
        }
        else
        {
            anim.SetBool("running", false);
        }
    }
}
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.

prisma birch
#

So I have been going absolutely crazy trying to find the culprit of this twitch on my player character's left arm. At first I thought this might be an animation problem (the hints and IK controls are the visualized gizmos) but none of them are moving in a way that should cause this. The twist is this only happens in some of my scenes. Does anyone know what I might be missing?

static matrix
#

is there a fix the non-uniform parent thing? or do I just have to suffer

leaden ice
static matrix
#

but what if I have to?

leaden ice
leaden ice
static matrix
#

it seems ineffecient to make a different model for every stretched cube that happens to have children

leaden ice
#

show me your hierarchy, I'll show you how you can rearrange it

static matrix
#

ok ok one second

leaden ice
#

you are doing this:

Cube (MeshRenderer, scaled)
  Child```
#

You should do this:

Empty Parent
  Cube (MeshRenderer, scaled)
  Child```
static matrix
#

bro at the start of this project I was making all of my mats emissive 💀

steep herald
#

is there an existing attribute/easy hack to have a field of a subclass be serialized above the fields of their parent class in the editor?

pallid cedar
#

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

prisma birch
leaden ice
#

Try to keep your objects within ~1000 units from the origin

prisma birch
leaden ice
#

if you have a large world you will need to use a floating origin technique

#

Otherwise this will be a constant issue

prisma birch
leaden ice
#

the distribution is such that they are much more concentrated around the origin

#

and it drops off very quickly

#

half of all possible floating point values are between -1 and 1

#

float is a 32 bit value so only a finite number of numbers are possible to represent

prisma birch
#

Yeah that makes sense. I'm just confused why it's only presenting itself on one aspect of the animation and no others.

leaden ice
#

as you get further from the origin, the distance between these values increases, hence less precision

thin aurora
leaden ice
#

under the right chin

thin aurora
#

I guess those are the ones who can't get an accurate value

#

The rest probably has some sort of precise value

#

If you move the character it probably happends to the rest too?

olive karma
#

hey, so Im making a game and I need to code so that the camera and the character are 0.266m away from each other so I coded a script that makes the camera always be 0.266 more on the Z axis but now when I look the other way I see my own body

#

and I did that cuz I want the player to be able to look down and see his legs

#

can someone suggest something that can make for example the character always teleport 0.266 behind the camera on the Z axis in that rotation, cuz I programmed the character to rotate and move with the camera

prisma birch
#

It seems the only thing behaving differently is that arm

olive karma
#

!image

#

can I post images here?

#

I am trying to make this game where the distance between your character and the camera is 0.266, the camera is in front of the player and when you look down you see your own body. Everything works well but when you start rotating the character does rotate but since the camera is 0.266m in front of it and you rotate 180° you see your own eyes.

#

How do I fix this issue I brainstormed of ideas how I can fix this but just can't implement them. I tried making the character basically orbit the camera while rotating and the same with the camera. Can someone please try to help me?

rigid island
#

eh just cull the face meshes from the camera

olive karma
#

but its also doing it with the legs so if I disable viewing the legs I wont see them in the front and I want to see them

rigid island
#

if you rotate past that your body would turn

olive karma
#

yea but I just made code that rotates the camera anywhere while moving the character with it

olive karma
olive karma
#

do I have to tho

rigid island
#

also part of the problem though i bet is near clipping plane

olive karma
#

I dont think so

#

well I guess I am going to change the code

#

ty

vast current
#

Ive got an array of vector3s where i want voxels to be placed using a custom mesh renderer, does anybody know how i can cycle loops through the positions and create the voxel faces at each one, I can't find a tutorial just for this

vast current
#

i've got that, im just confused on what all the vertices and tris need to be

versed loom
#

Are these animation events bad for performance, since it says they are the same as SendMessage?

lusty echo
#

Hi, I'm attempting to create a low-poly model of a room and would like to animate each component - the planks, doors, windows, etc., - flying into their correct positions. I've considered using a shader and vertex color but would prefer a method that offers more control. Does anyone have suggestions on the easiest way to achieve this?

steady moat
lusty echo
steady moat
#

A 1 time animation ?

lusty echo
#

Finally two animation, first when room appears, and then element fly out when before I remove room

steady moat
#

Just use an animator if it is always the same motion or use code otherwise.

#

Definitly not shader

lusty echo
#

But it's ok if you have a lot separate meshes instead of one

#

Because I have to have all elements separately

#

To animate every planks etc

steady moat
#

Yes, you can as many as you want item.

lusty echo
#

Ok so other question, I imported model from blender and Its automaticly created a prefab with all meshes, and right no I want add script to this prefab end get all children meshes how I can hande it?

leaden ice
dusky pelican
#

Hello, i made a ScriptableObject for creating quests. But the problem is when i start the scene some values are going default every time here is the before start and after start

#

Just three of them going default

leaden ice
#

the instance ID of the second object shows that it was created at runtime

#

the first one is an asset

dusky pelican
#

Ah so

#

I need to make an init

#

for it

#

Thank you! I will do it. Probably %99 will be done

leaden ice
rocky jackal
#

I need some help with rotations. I need to calculate the difrence between 2 objects and apply it to a third one but i get a difrent rotation everytime and i couldnt find a solution online.

leaden ice
#

should be that

rocky jackal
austere lodge
#

hey im having issues with a model i rigged with maximo does anyone reconize the issue?

austere lodge
#

Sorry

weak nexus
#

okay, so my friend followed some of sebastian langue's prod landmass generation and we're not done with the series yet and ours is slightly different than his but not too different, but our issue anyways is that our chunks are inconsistent and dont offset correctly as shown here, only some of them are connecting fine but very few only

#

i dont know which part of the code would affect this, i do know the codebase because i learned it a bit as well but i don't know where to look for this

#

we got past threading to the "seams" episode

orchid bane
#

Is it important to keep namespaces? Rider constantly puts them in for me but I don't feel a need for them

leaden ice
#

they are an organizational tool only

#

they also let you use the same class name twice (by having it in different namespaces)

pure cliff
#

I want to say in some way or another your compile time improves, because without namespaces the compiler basically has to search your entire project for everything, whereas namespaces substantially reduce its search space for <thing>

latent latch
#

I usually divide my enums out via namespaces

pure cliff
#

I think also it helps with recompiling, because the compiler can check if a given namespace is "dirty" and determine if it needs recompiling?

#

Like if you have files in NamespaceA and NamespaceB, and you make changes to a file in NamespaceB, it will only recompile the stuff for NamespaceB, because it can tell that nothing changed over in A.,.. I think

#

compilers are like 95% ancient black magicks so, its prolly 1000x more complicated than that

jaunty sleet
#

Does anyone know the difference between declaring a two dimensional array like this: int[,] array; or like this: int[][] array; ? Is the difference just that with the second option you can have different length arrays in the second dimension?

pure cliff
jaunty sleet
pure cliff
#

Depending on the purpose of the object, you may also wanna consider a Hashset<Vector2> or etc

jaunty sleet
#

It's arrays of indexes, so I think this one makes more sense

#

For the state of user choices in different parts of my menu, so when they come back to it the same choice is still selected

stark thicket
#

Hey all, I was wondering if any of you have worked with WebCamTextures before. I am trying to get the webcam into a 48x48 Color32[], and figured a good way to do that would be to read the WebCamTexture in as a 48x48 texture. However, after calling webcamTexture.Play() it seems to immediately change the texture back to 1920x1080. If I don't call webcamTexture.Play(), it seems to be stuck at 16x16, I have no idea where it's getting that from. Any help is MASSIVELY appreciated!

spring creek
cobalt gyro
#
    {
        currentWeaponIndex += (int)Input.GetAxis("Mouse ScrollWheel");
        weapon.currentWeaponData = weapons[currentWeaponIndex];
        
        if (currentWeaponIndex < 0)
            currentWeaponIndex = weapons.Count - 1;
        if (currentWeaponIndex > weapons.Count - 1)
            currentWeaponIndex = 0;
    }``` for some reason the variable "currentWeaponIndex" isn't looping, does anyone know why?
stark thicket
lapis egret
leaden ice
#

you're also doing weapon.currentWeaponData = weapons[currentWeaponIndex]; before you wrap the index

#

so you'll end up getting an error before it happens (and also stopping the wrapping code from running)

lapis egret
#

wrap the index?

simple egret
#

The two if statements. Wrap the value around for it to not get out of bounds

#

But yeah and the 120, -120 will actually depend on your Windows settings, you're better off checking if the value is positive or negative and adding/subtracting 1 accordingly

lapis egret
#

Ahh yeah I see it now

elfin tree
#

Can anyone point me towards a solution for using the New Unity Input System across multiple scenes as it's not possible (or I do not know how) to assign functions and objects from other scenes to be triggered by key presses? Thanks

leaden ice
#

and there are tons of ways to do that, such as:

  • using singletons
  • using opportunistic assignment (assigning references when instantiating things, or colliding with things)
  • using Find-style functions like FindWithTag
#

with the input system in the mix it would just involve either your scripts getting references to the input system constructs, or the scripts that handle input getting references to the other scripts to do stuff. Either way can work

elfin tree
leaden ice
#

they are normal C# events

#

that is one possible way to do it

elfin tree
#

Oh okay, will read into that, thanks.
Do you happen to know how to access them?

#

Or could point me towards the right doc

simple egret
#

inputActions.yourActionName.performed += ...

leaden ice
#

that's not what you need

#

depending on what _playerInput is, will determine the answer

elfin tree
#

It's a default New Input System thing (afaik)

leaden ice
#

if it's an instance of the built in PlayerInput component, you'd do something like _playerInput.actions["MapName/ActionName"].performed += MyFunction;

simple egret
#

Okay so that doesn't require you to subscribe to events from your own script

leaden ice
#

you could also just assign the unity event to a function on the object itself, and then delegate from there however you wish in code

#

either with your own event, or... whatever else you want to do

simple egret
#

This component does it for you, and you have some options to have the events relayed to you

elfin tree
simple egret
#

It's one of the few ways to receive input. You could also tick "Generate C# class" on your input actions asset, and then create a new instance of it here and there, on each script that needs to receive input

#

Even in multiple scenes

#

On multiple objects at once

leaden ice
#

note then that those instances will be separate

elfin tree
#

hmm, so does the function have to be something special?

leaden ice
#

which might be ok for you and might not

elfin tree
leaden ice
leaden ice
#

you don't call it

#

get rid of the ()

elfin tree
#

Ah and method needs callbackcontext, i see

leaden ice
#

second - it has to match the delegate type:

Action<InputAction.CallbackContext>```
#

yes

#

it needs that InputAction.CallbackContext parameter

#

and to return void

grand gale
#

in inspector, i have a small silly button to generate nodes called Create
what this does is call Create on a class Navmesh
Create goes through all objects in the scene (this is gonna be changed since its slow and kinda pointless, but it works for now), and creates a node for each vertices each object has
Nodes are valid, their positions and everything.
However, in the following code:

public void OnDrawGizmos() {
    foreach (Node node in Nodes) {
        foreach (Node connection in node) {
            Gizmos.DrawLine(node.position + Vector3.up, connection.position + Vector3.up);
        }
    }
}```
The lines only appear for a frame (unless the scene view is frozen, such as doing something outside of the scene view, but still a frame technically), why is that? They also don't re-appear, even though ``Nodes`` doesn't get cleared or anything
orchid bane
#

I have a camera controller which is supposed to follow the player. It subscribes to the player spawner to start following after the player is spawned. However the player spawner happens to work before the camera controller (both things happen in awake). How would you solve such a problem?

elfin tree
#

@leaden ice @simple egret any idea what could wrong here?

elfin tree
#

If the string is wrong it will give a different error so "Game/Toggle Console" is correct

elfin tree
#

_playerInput.actions["Game/Toggle Console"].performed += GameServices.ConsoleKeyInputsTemp.InputToggleConsole;

leaden ice
elfin tree
leaden ice
#

and GameServices.ConsoleKeyInputsTemp?

elfin tree
leaden ice
#

so - are you sure that's not null?

#

Yeah it's probably null

#

it's not getting assigned until Start

elfin tree
#

ahhh...

#

let me give that a try

leaden ice
#

And you're doing this subscription in Awake

#

you should reverse it

#

That GameManager thing should be Awake

#

and the subscription should happen in Start

hidden flicker
#

how could I reference the player rigidbody to the grenade? i want to add the velocity of the player to the velocity of the grenade gameobject

leaden ice
hidden flicker
#

how would you do that

leaden ice
#

have it directly reference the player's RB

#

and add the velocity when throwing the grenade

hidden flicker
#

how might i have it directly reference it and get that information to the script

leaden ice
#

make a public field

#

drag and drop it in

elfin tree
#

@leaden ice that was indeed it (plus other extra me errors), tyvm, i'm now able to reproduce it for other actions/scenes!

leaden ice
#

I would do it something like this:

public Rigidbody playerBody; // drag and drop
public Grenade grenadePrefab; // drag and drop the prefab here

void ThrowGrenade() {
  Grenade newGrenade = Instantiate(grenadePrefab);
  newGrenade.Throw(playerBody.velocity + whateverOtherVelocityYouWant);
}``` @hidden flicker
hidden flicker
#

ok thank you

naive swallow
#

I have an interface that is only implemented on MonoBehaviours. If I make a variable of type interface, it doesn't serialize in the inspector, I think because it doesn't know it's a UnityEngine Object. I can't System.Serializable an interface either. Is there a way I can drag in a MonoBehaviour implementing an interface into a variable of that interface's type?

swift falcon
#

Is there a best practice for determining if a Rigidbody (not Rigidbody2D) is grounded? I'm working on a hierarchal state machine w/ a grounded super-state.

leaden ice
naive swallow
uneven monolith
#

U cant serialize interface iirc

stark thicket
elfin tree
#

Is there a simple way to use lighting settings from an additive scene, loaded at runtime?

#

(instead of settings from the scene used to load the additive scene which happens by default)

weak nexus
hidden flicker
#

I'm trying to get the grenade to invoke the explode method in the explosion script, but i'm getting the "object reference not set to instance of an object" error.

leaden ice
#

sounds like you didn't assign explosion in the inspector

uneven monolith
hidden flicker
#

16, grenade

uneven monolith
#

Your ss doesnt show lines ;-;

hidden flicker
#

the prefab has the script, though.

leaden ice
#

it's the one with invoke

hidden flicker
#

oops lmao

leaden ice
uneven monolith
#

Yeah, sounds like it

hidden flicker
#

the grenade prefab has the explosion script

leaden ice
uneven monolith
#

Show inspector of grenade

leaden ice
#

this looks like a totally different script

hidden flicker
#

wait wrong screenshot

leaden ice
#

where's the Grenade script here?

hidden flicker
#

at the top

leaden ice
uneven monolith
#

No that has just capsule collider, rigidbody, and explosion

hidden flicker
#

theere we go

leaden ice
#

the fields in your inspector aren't matching the ones in your script. That means you have two different scripts or you haven't saved your code

hidden flicker
#

solved it. the reference to the explosion script said explosion, so i thought it had autoreferenced

#

it had not

uneven monolith
#

Autoreferencing isnt a thing in unity

||😭😭||

hidden flicker
#

i mean i think it's done it before???

elfin tree
leaden ice
#

you are misremembering

hidden flicker
#

:(

swift falcon
#

I'm working with a hierarchal state machine, and in my grounded super-state (currently my only existing state), for some reason, my character's rigidbody just won't move. The following is my code in FixedUpdate().

  //Vector3 moveDirection = new Vector3(move.x, 0, move.y);
  //moveDirection = _sc.Player.transform.TransformDirection(moveDirection);
  //moveDirection *= _sc.Speed;


  _sc.PlayerRB.MovePosition(new Vector3(move.x, 0, move.y));
leaden ice
#

at the very least I would expect _sc.PlayerRB.MovePosition(_sc.PlayerRB.position + new Vector3(move.x, 0, move.y));

Also why are you calculating this moveDirection variable and then ignoring it?

swift falcon
leaden ice
#

my comments still stand

swift falcon
#

move = _sc.PlayerInputManager.imMovementInput;

^^^ This is being set in OnEnter().

leaden ice
#

none of that changes what I wrote. It reinforces it actually