#archived-code-advanced

1 messages · Page 5 of 1

elder compass
#

I’m low-mid tier in html and python

upbeat path
#

html is not a programming language and python barely so

fresh salmon
#

These tutorials are especially nice because you can try out the code in the browser directly

elder compass
#

I know the MERE basics of C#, like how to declare a variable, how to write “Hello World” etc

#

It’s just that I’m a games development student, and I’m trying to learn C# because the software at where I am is a bit naff (Heard of Construct 2?) - as well as learning no programming

rugged radish
#

start with thinking in python and just looking up the c# syntax for that, they're both general programming languages and pretty easy to transition to

upbeat path
#

then look at the MS stuff, it' can't hurt

elder compass
#

And I wanna start using Unity to up my game in games development.

upbeat path
#

Better to be proficient in C# before tackling Unity than to try to do both at once

elder compass
#

Ok

#

What about java? They’re similar in syntax aren’t they?

upbeat path
#

no

#

javascript is similar in syntax to c#

elder compass
#

Are there any programming languages that are similar to C#?

upbeat path
#

Beef

tender light
trim raven
#

ok i was able to find the visual studio editor but it still fails

upbeat path
elder compass
#

So would it be ideal to learn Java, before learning C#?

tender light
regal olive
#

Yes, I think starting with C# is okay. When you get comfortable with writing code, testing and design you can pick up Unity for extra challenge.

tender light
placid violet
keen cloud
#

I posted in code general im coming to here now

#

how come enabling a box collider from a script isnt triggering an OnTriggerEnter2D event?

sly grove
#

unfortunately

keen cloud
#

how would i make this work this way

#

is there a workaround

#

i mean i know a workaround but im looking to see why this doesnt work first

lavish sail
#

because technically the thing doesn't enter it when activated

keen cloud
#

:(

wintry wind
#

Hi. I have a screen space ui. I have a script that works perfectly where I put a UI square on top of the target (first person camera). I want the square to stay in the screen (on the border) when the target leaves the viewport so the player knows where to turn

#

Any idea how to do this? I’ve tried way too many things. I can already remove it when it is facing the back of the camera but there’s an angle where the world space conversions start giving crazy values

turbid cairn
#

Question guys and gals:
I have ascript that almost works. but i need your help to solve the issue.
Im targeting a 3D object thru a worldtoscreenpoint and showing it on a canvas UI.
that works. but i want to clamp the border in a circle, so the target icon doesnt go outside the circle, but still tracks the target.
here is the code. i need the last part to work with the following bit to work together.
Using the clampMagnitude with the anchorPos.
Right now, it just places the icon on top of the camera 0,0,0 position. And doesnt move.
here is the code:

            //2D Icon following a 3D object on a canvas.
            rawImage.texture = reticle;
            targetXY = thisCam.WorldToScreenPoint(target.transform.position);
            Vector2 anchoredPos;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(parent, targetXY, thisCam, out anchoredPos);
            //Clamping the Icon inside this radius. How can this work with following the 3D object so its clamped but still move towards the object?
            image.anchoredPosition = anchoredPos;
            var positionXY = new Vector2(anchoredPos.x, anchoredPos.y);
            positionXY = Vector2.ClampMagnitude(positionXY, boundryRadius);
            //Positioning the Icon to match the canvas and the 3D object.
            image.anchoredPosition = anchoredPos;

im super greatful for all help.

regal olive
#

how to i get the device and and ad id? And directly from within the editor or even android studio for easy copy pasting?

fresh vortex
regal olive
fresh vortex
#

it's a code related channel

regal olive
#

these channels are usually for anything generally related to unity. besides most of unity stuff is totally in the editor, so it's understood that non-code related questions are allowed

fresh vortex
#

"Ask questions and discuss anything related to advanced coding concepts in Unity"

#

I don't see how is this related to advanced coding

#

code channels are for code problems

regal olive
#

how do I get the ad id from the editor?

fresh vortex
placid shell
#

wondering, if i alocate more memory than i need for something with Marshal.AllocHGlobal() will this cause issues or will it just be inefficient?

placid shell
hazy epoch
#

Anyone know why Plastic SCM constantly adds files to the Pending Changes list that haven't actually been changed...and how to stop it from doing that?

wispy rock
#

building linux il2cpp player requires a linux sysroot package to be installed.
LinuxBuild support both mono and IL2CPP is installed.
Unity version 2021.2.19f1 M1 Chip
Could anyone help with this?

next marsh
#

Does C# still not support operator overloading using extension methods?

novel plinth
#

since when they changed that anyway 🧐

timber flame
#

🤣

placid shell
#

how would i access a rendertarget of a render texture or really of anything that has one in unity? (i know it is possible according to the unity docs, it just doesn't really explain how)

dark oar
#

Hello, I am fairly new to Unity 3d. So, I've been trying to make a FPS game in unity using raycasts for a college project. I've used the shooting code from Brackey's YT tutorial (I think so, I copied the code ages ago). Shooting seems to work on simple 3d objects like a cube but when I apply the "Target" component to a whole enemy AI character, nothing happens. If someone is willing to help me, I would more than love to explain more on the issue through dms!

I wrote this in advanced since Raycasts sound complicated omg

flat marsh
#

You should explain outside of dms in #💻┃code-beginner so everyone who can help has the chance without the need for one person clto commit to it

dark oar
#

Okayy I will then

placid shell
#

it would be nice if i could just get a list of all render targets but it seems no one in the direct x discord group knows of a way to do that

ocean raft
#

Hello, is it possible at all to have the mouse cursor appear on a completely different camera?

sly grove
#

The mouse cursor appears on the screen, not on any camera

ocean raft
#

ok...hmm

#

what I'm trying to do tho is control a cursor or the cursor on a canvas displayed on a different camera

#

as in a cursor within the monitor

sly grove
ocean raft
#

ye but new input system go brrrr

sly grove
#

input system is irrelevant to the question you asked

ocean raft
#

cheers

undone coral
#

doesn't graphic raycaster still work through the second camera?

#

you can use the event system to find the position of the pointer in that camera

ocean raft
#

however we found out that we can straight up interact with the hidden menu but its completely misaligned but doesnt move around if we move either A) the cam or B) the canvas itself

#

all I know is I've tried getting the mouse world position and the new input system forces me to use their system but I dont know exactly how to use theirs

ocean raft
#

yeah so how it currently works is a main camera looking at the tv

#

whilst a separate camera is viewing the menu from somewhere else and using a render texture for the tv

undone coral
#

try messing with the camera field on the graphic raycaster on the canvas

#

attached to that secondary camera

#

yeah

#

i hear you

#

try setting the camera field in the graphic raycaster to the secondary camera

ebon fog
#
using UnityEngine;
using System;
public class FixedCallbackManager : Singleton<FixedCallbackManager>
{
    //public Callback physicsSync;
    public Callback spawn;
    public void Update()
    {
        spawn.Update();
    }
    [System.Serializable] public class Callback
    {
        public float deltaTime;
        private float time;
        public void Update()
        {
            if (deltaTime < 0.001) deltaTime = 1;
            time += Time.deltaTime;
            while(time > deltaTime)
            {
                time -= deltaTime;
                callback();
            }
        }
        public Action callback;
    }
}
#

I keep getting this error and I don't know why

#

NullReferenceException: Object reference not set to an instance of an object
FixedCallbackManager+Callback.Update () (at Assets/TL-XRI/Managers/FixedCallbackManager.cs:24)
FixedCallbackManager.Update () (at Assets/TL-XRI/Managers/FixedCallbackManager.cs:11)

undone coral
#

what is your goal?

ebon fog
#

something akin to a seperate fixed update function

undone coral
#

is it supposed to interact with things in the scene?

ebon fog
#

So I could have multiple fixed updates running at different speeds

#

I would subscribe other methods to it

undone coral
ebon fog
#

floats for time in between

undone coral
#

so for example, 2x a frame, 1x a frame, once every 2 frames..

undone coral
#

or what the meaning of that would be?

ebon fog
#

floats for seconds between

#

I meant

undone coral
#

what is the gameplay objective?

#

i am suggesting your ead that blog post because, probably your idea of how time and pacing works in unity is wrong

#

would you like ot learn how it really works?

#

it would be helpful to know what hte gameplay objective is

ebon fog
#

The only problem I'm having is not being able to call an Action

undone coral
#

trust me that's not the problem you're having

#

i know a lot more about this than you

#

what is your gameplay objective?

ebon fog
#

seperate update loops running at various intervals, to save on performance, because they do not need to be ran every frame, or even every fixed fram

undone coral
#

for example, are you trying to improve rendering performance, or something in your game logic that is expensive to compute?

ebon fog
#

an example could be pathfinding

undone coral
#

okay

ebon fog
#

or a global spawn method that is synced between multiple spawners

undone coral
#

pathfinding does, but also, it usually is not

ebon fog
#

I know

#

It's mostly for the experience of making it work I guess

undone coral
#

or a global spawn method that is synced between multiple spawners
this doesn't sound like it has anything to do with trying to make your own player loop. that's the name of the thing you are trying to do, but currently incorrectly, but it would be the wrong thing to use anyway.

ebon fog
#

I know

undone coral
#

you can learn unirx, then this can be as simple as

ebon fog
#

honsetly, the I'm facing, is that I get an error whenever I try to call an action, regardless of whether there is anything subscribed to it or not

undone coral
#
int period = 5;
void Start() {
 Observable.EveryUpdate()
              // this is monotonic
  .Where(_ => Time.frameCount % period == 0)
  .Subscribe(_ => {
    // whatever you want to execute every period frames, e.g. every 5 frames
  })
  .AddTo(this);
}
#

this will be much more valuable to learn

#

because this obviates the entire thing you're trying to build

#

if you knew what unirx was

ocean raft
undone coral
undone coral
#

in other scripts

#

very succinct, simple, elegant, it already has the "callback" thing you are imagining - that's what a subscribe is.

#

@ebon fog does that make sense?

undone coral
#

do you have a graphic raycaster ont he secondary camera?

#

if not, add one

#

now you can send event system events to its screen space canvas

ocean raft
#

oh damn is it a component that I need to add then?

undone coral
#

i think the screen space canvas might have an "event camera" field too

#

i forget

undone coral
#

you definitely have a graphic raycaster on your main camera's canvas

#

look carefully

#

i mean, not definitely, but probably - if UGUI has been working, you have one

ocean raft
#

ye got it

undone coral
#

or are you just getting mad

#

even though like 90% of the code in the snippet you posted doesn't make sense

violet valve
#
using System;
public class FixedCallbackManager : Singleton<FixedCallbackManager>
{
    //public Callback physicsSync;
    public Callback spawn;
    public void Update()
    {
        spawn.Update();
    }
    [System.Serializable] public class Callback
    {
        public float deltaTime;
        private float time;
        public void Update()
        {
            if (deltaTime < 0.001) deltaTime = 1;
            time += Time.deltaTime;
            while(time > deltaTime)
            {
                time -= deltaTime;
                callback();
            }
        }
        public Action callback;
    }
}``` Reposting this for @ebon fog since I'm curious.
#

Which lines are 11 and 24?

ebon fog
ebon fog
#
using UnityEngine;
using System;
public class FixedCallbackManager : Singleton<FixedCallbackManager>
{
    //public Callback physicsSync;
    public Callback spawn;
    public void Update()
    {
        spawn.Update();
    }
    [System.Serializable] public class Callback
    {
        public float deltaTime;
        private float time;
        public void Update()
        {
            if (deltaTime < 0.001) deltaTime = 1;
            time += Time.deltaTime;
            while(time > deltaTime)
            {
                time -= deltaTime;
                callback(); //error is here
            }
        }
        public Action callback;
    }
}
violet valve
#

Okay, I actually don't see where callback is being set, ever. Is it managed outside this class somewhow?

ebon fog
#

how do you set it

violet valve
#

callback = MethodName.

ebon fog
#

?

viral edge
#

You'd have to have already made the function or method somewhere else.

ebon fog
#

I want a way to create something similar in function to the RenderPipeline.beginCameraRendering, Is that not an Action?

violet valve
#
private void SomeMethod() {
    Debug.Log("Do something"):
}
void Start() {
    myAction = SomeMethod;
    myAction?.Invoke();
}```
ebon fog
#

can you still add methods to that with += ?

violet valve
#

An Action is a method with no parameters. It is in the system namespace, not some unity mumbo jumbo.

#

No, it's not an event. Use public event Action MyEvent; to make events.

ebon fog
#

oh

#

that was my problem then

violet valve
#

Ahh, yes. Better to learn about observables, events, delegates, etc. without also trying to build a game at the same time.

#

In this case, Action is the delegate. If you wanted your method (or event, whatever) to take an argument, you would need to use one of the generic forms Action<T>, or for two arguments Action<T,T>, etc.

ebon fog
#

still getting an error

#
using UnityEngine;
using System;
public class FixedCallbackManager : Singleton<FixedCallbackManager>
{
    //public Callback physicsSync;
    public Callback spawn;
    public void Update()
    {
        spawn.Update();
    }
    [System.Serializable] public class Callback
    {
        public float deltaTime;
        private float time;
        public void Update()
        {
            if (deltaTime < 0.001) deltaTime = 1;
            time += Time.deltaTime;
            while(time > deltaTime)
            {
                time -= deltaTime;
                callback(); // error is still here
            }
        }
        public event Action callback;
    }
}
#

it has nothing subscribed yet

violet valve
#

Yeah, then that will happen. The value of an event is null if nothing subscribes to it.

#

You can't execute a null method (or list of subscribers in this case).

ebon fog
#

so how do I stop it when there is nothing subscribed

violet valve
#

How much programming experience do you have?

ebon fog
#

I've only used Unity, but I don't think I'm terrible.

violet valve
#

Oh, it's fine!

ebon fog
#

sorry

violet valve
#

No problem... let's finish this one.

ebon fog
#

I didn't want to interrupt the other channels because they were in the middle of something though

violet valve
#

So, you have a goal in mind that you want to execute callback(), but don't know if the value might be null, right?

ebon fog
#

yes

violet valve
#

Okay. How, using the computer, can be determine if the value of callback might be null, then?

ebon fog
#

I feel dumb

#

thanks

violet valve
#

😄

#

I hope that means you get the idea and not that this is out of reach.

ebon fog
#

I didn't expect the callback to be null if nothing is subscribed to it since everything else only stays not null unless you set it null

violet valve
ebon fog
#

yes, but the arrays don't complain when the length is 0

#

I think

violet valve
# ebon fog I think

Right, because an empty array is still an array, as long as it has been instantiated like int[] ints = new int[0], though I've... never written that out before...

ebon fog
#

thanks again though

maiden turtle
#

you can reassign to a sum too
action = action + anotherAction

ebon fog
#

Omi already solved this for me but thank you for trying as well

maiden turtle
#

it's just that events are generally annoying, I prefer just delegates

violet valve
maiden turtle
#

yes you can add a delegate to a delegate

#

if they are the same type

violet valve
#

Just as a test...

maiden turtle
#

((Action) ShowQuitModal) + ShowQuitModal will work I'm pretty sure

violet valve
#

Well, look at that. Learned somethin'.

#

I guess that puts the "group" in method group. Thanks!~ @maiden turtle

maiden turtle
#

it forces it to make the first delegate from the method, then the second is implicitly converted as an argument to + operator overload of the delegate type

#

I don't know what you mean by group in method group

#

@violet valve

violet valve
#

ShowQuitModal, with it's signature in this instance is a "method group" (before being cast to Action). You apparently can't add them to each other, but an Action will take a method group through the + operator. I don't know why they're called "method groups" and not just methods internally.

maiden turtle
#

I think that means an unknown overload of a method. like there could be functions with the same name that take different arguments. hence a group

violet valve
maiden turtle
#

and it's a good thing they don't create delegates unless you explicitly assign or cast to a delegate type

#

delegates are objects, they aren't free

violet valve
#

This is interesting, and I might see how I can break from events in some cases. I didn't come here to learn things today, but y'know~

grizzled sonnet
#

Hi there! I was just wondering, does anyone know what the new Input System package does to the game's performance? My team and I are trying to decide how to approach keybindings. And most of the pros of the Input System that I find online are about how easy it is to use and how it takes a lot of work away from the programmer. But we're a little iffy about just downloading packages into the project without fully understanding what it does to it. Would the game run faster with the new Input System or with a custom keybinding script? Thanks!

violet valve
grizzled sonnet
#

OH so it really only runs when it detects input, instead of checking for input every frame?

violet valve
#

If by using your "custom keybinding script", you mean building something relies on the Input class, it'll be inherently worse.

violet valve
grizzled sonnet
#

OOOOHHH icicicic

#

Are there any cons to using the Input System?

violet valve
#

It has a massive learning curve.

grizzled sonnet
#

Hahahaha fair enough

inland delta
#

however its really worth

violet valve
# inland delta however its really worth

@grizzled sonnet It is. The first time you run through it may take some hours, depending on your deduction skills (and until you realize that it just requires a handler class that satisfies some generated interfaces), but I can whip up an input system in 5 minutes because I know how it works. It's great, but it's not as immediate as tossing code into the Update loops of all your MonoBehaviours, which frankly should never have been how it worked in the first place.

grizzled sonnet
violet valve
#

I will tell your boss that the old system is for sissies.

grizzled sonnet
violet valve
#

The old system is not for programmers who can comprehend events and delegates. If you can reliably use the whole C# language, it should be immediately understood why input polling does not need to be run as many times per second as your game generates frames.

#

Tell them that.

#

The old system, however, is great if you need the entire input system to be understood by your artists and marketing team if they will be helping create actionable gameplay during crunch time, and you haven't feature-locked your inputs. @grizzled sonnet

grizzled sonnet
undone coral
#

for your game?

grizzled sonnet
undone coral
#

like to implement a bunch of gameplay?

grizzled sonnet
undone coral
#

okay

#

you're going to wind up using Input. in so few places, that you should use Input System instead

#

you're already in a really good place

grizzled sonnet
#

We haven’t implemented gameplay yet. We’re currently focusing on the Options/Settings of the game. And we’re trying to make the part where you can change your keybinding

undone coral
#

pretty much everywhere you're doing raycasts on Input.mousePosition you should use eventsystem instead

undone coral
#

you can use an asset to help you with the rebinding UI, these things have traditions and you should just copy what people expect

undone coral
#

what kind of game is it?

undone coral
#

do you know that there is an event system physics raycaster for 3d objects?

grizzled sonnet
#

I’m sure someone does, but it’s not me MoxPanic

undone coral
#

to find out what you should do

#

it really depends on the game though

violet valve
# undone coral it really depends on the game though

Either way, the takeaway is that polling routines are bad and by using the new input system, you may or may not make huge gains in terms of performance. It's good to know how it works and not tailor your environment to a low common denominator if it is a commercial product.

novel plinth
#

New inputsystem is nice, but the workflow is not... Glad we have much freedom to make our own thin wrapper with it compared to the legacy... The person who designed it proly just a coding nerd..

upbeat path
manic charm
tough knoll
#

The way my player control works is kinda like quake, it generates timestamped commands each frame (they need to be saved & sent during networking anyways to make sure the client and server agree on stuff) so I feel like the polling method is more straightforward. But are there real gains to using the newer system?

deep peak
tough knoll
#

thanks

#

Sounds like it would make axes easier

#

Right now I have every possible axis defined so that they can be mapped to controls at runtime : S

hollow prairie
#

For my game i am caching assetbundles via UnityWebRequest.LoadFromCacheOrDownload

How can i give a script an assetbundle name and asset name from that bundle, and then instantiate it from the cached bundle?

#

Ah, i think i get it

#

If i give it a url thats already downloaded it loads it from the cache?

#

From there i can just load the asset

mystic widget
#

Hi guys,

I was wondering if an Action could store multiple variables at once. I.e.
-I have a function that requires: Name,Age,Occupation
-I have 40 clients. I need to run this function in sequences
-Each time it runs this functions many things happen in between so I can't have them run all at once
-Each time an Action finishes it will remove itself from the list then go onto the next one.
-Depending on the occupation, there might be cases where more actions get created in the same category but it will process on a different list.

undone coral
#

you shouldn't try to cache them yourself

#

caches expire and the content has to be immutable

short atlas
#

what do i need to point to to access the TextMeshPro component thats a child of a button? I tried with TextMeshProUGUI and that still doesnt work

high karma
#

yourob.transform.GetChild(indexhere).GetComponent<TextMeshPro>();

i assume they are on same object parent

short atlas
#

its ok, i fixed it by just making a public GameObject and dropping the Text(TMP) into it, now ill just access it from there

short atlas
upbeat path
short atlas
#

alright thanks

upbeat path
short atlas
#

because the TMP_Text is generated by a nested for loop (which is used to make a grid of buttons) so that TMP doesnt exist before runtime

upbeat path
#

ok, good response

short atlas
#

if i do this to access TMP what do i need to initialise 'child' as, because if i make it a GameObject then it will give me errors

#

like it will say "Cannot implicitly convert type TMP to GameObject" which makes sense but i have no idea what i should make child then, if i cant make iot a gameobject.

high karma
#

var parent = new GameObject();
var child = new GameObject();
child.AddComponent<TextMeshPro>();
child.transform.SetParent(parent.transform);
parent.transform.GetChild(0).GetComponent<TextMeshPro>();

#

Something like this

short atlas
#

yeah using var helps

#

just did it xD

devout hare
#

Using var is a pretty bad idea when you don't know what the type is. Whenever you do GetComponent<x> the type is x

high karma
#

I agree. Using var on transform foreach will turn it into object. But for the most part it should be correct.

short atlas
#

makes sense

short atlas
high karma
#

Assuming the component is not null. you can just set it after getting the component.

(getthecomponenthere).text = "blahblah";

short atlas
#

woudl this mean its null then?

#

i've been getting this a lot

high karma
#

Yes. I dont know how you setup your object but the index and the textmeshpro must be a child of the parent you getting component from.

#

If youre not sure about the index but know there is only 1 component of this type then use yourOb.transform.GetComponentInChildren<TextMeshPro>()

short atlas
#

so the GenController is the parent here

#

and SpawnedTile is spawned as a child of GenController

#

yeah and it just spawns a clone of a prefab

high karma
#

How does the original button looks like

short atlas
#

as in the prefab?

high karma
#

Yes

short atlas
high karma
#

The hierarchy.

short atlas
#

ill send sc one sec

high karma
#

Show the button child.

short atlas
high karma
#

Change your transform.GetChild from 1 to 0

#

Because first index start from 0

short atlas
#

when i do that it just only spawns one button clone and i get this error message:

high karma
#

Change the last line from GenController.transform into spawnedTile.transform.

short atlas
#

same thing happens

high karma
#

Whats the latest code. Also is Text (TMP) has TextMeshPro component.

short atlas
#

should i send the whole function?

#

oh wait i think i see the error

high karma
#

TextMeshPro textMesh = spawnedTile.transform.GetComponentInChildren<TextMeshPro>();
if (textMesh == null)
{
Debug.Log("nooooooooooo");
}

Try check if it exist.

short atlas
#

yeah so it says "nooooooo' but thats because i still need to get another child, because like this we are only in 'Button (clone)", but we need to get into that child as well to access TMP

high karma
#

Using getcomponentinchildren traverse the child.

short atlas
#

hmm, but by getting 'spawned child' it should still work...

high karma
#

Are you sure you have added textmeshpro to text (tmp) object?

short atlas
#

im just cloning a button which has it by default

#

i have an idea

high karma
#

TextMeshPro textMesh = spawnedTile.transform.GetComponent<TextMeshPro>();
if (textMesh == null)
{
Debug.Log("nooooooooooo");
}

Try check if it exist.

#

Then perhaps its on the button itself

short atlas
#

yeah it says it doesnt exist

#

ill just reshape the button to not have a child but have the TMP on itself

#

nvm it cant have more than one graphic so it needs to ahve TMP as a child

high karma
#

I really dont know the setup of your project but you can do
(spawnedTile.transform.GetChild(0).GetComponent<TextMeshPro>() ?? spawnedTile.transform.GetChild(0).gameObject.AddComponent<TextMeshPro>()).text = "blahblah";

#

It basically just create new textmesh if there isnt one found.

short atlas
#

thanks anyway for the help

high karma
#

Edited.

short atlas
#

🙏

high karma
#

Im writing all of this in phone so i apologize for the messy code.

short atlas
#

yeah, ill try figure it out on my own. i still get the same NullReferencError

high karma
#

lol

#

I know it now

short atlas
#

lmao

high karma
#

the existing component you want to get is not textmeshpro. But rather textmeshprougui.

short atlas
#

BRUH

#

wtf

high karma
#

Yeah thats why i want to make sure its the right component on the object

short atlas
#

BROOO APPRECIATE IT

#

THANK YOU

calm ocean
#

Suppose I want to replace a serialize field of a parent field by making the type more specific.

public class A : ScriptableObject
{
    [SerializeField] private AParentClass FieldToReplace;
}

public class B : A
{
    [SerializeField] private new SubclassOfAParentClass FieldToReplace;
}

Is it possible?

high mirage
#

does anyone know how you can change the color of these black bars when using the pixel perfect camera component? i couldn't find any info about it on google

misty glade
calm ocean
misty glade
#

Your example is a little confusing because you're using generic names and not really saying what you're triyng to do.. but.. assuming your AParentClass and SubclassOfAParentClass have adequate editor/inspector integration, you'd just have B have an object of AParentClass

#

you'd design that logic in SubClassOfAParentClass, not in B

#

I don't know if this works in unity, I seem to remember walking down this path months ago and then giving up, but.. maybe try using a property that determines the type and gets depending on what it is

calm ocean
#

Let me replace the generic names with the actual problem I am facing, hopefully that will clear things up.

I have a CombatAction scriptable object that allows the player to do something and change the game to the next AGameState, which is also a scriptable object.

This CombatAction is a scriptable object that takes in an AGameState. I have a particular CombatAction that can should move to a particular AGameState called AttackState. The combat action needs to know it's specifically an AttackState so that it can initialise something for the state to work. So the idea here is that someone using the attack combat action scriptable object can drop drag and drop the attack state into the field.

#

I could just raise an exception if the given state is not the attack state, but I figured it would be better to add a constraint to the field.

#

Unless if that's not possible.

misty glade
#

What's your prefix A denoting, btw? ie, AGameState? Just "a game state"? if so, don't - just use GameState - is that an enum? some people consider it acceptable to postfix it with a word like Type if the base word is too short - like StateType, then you'd have things like:

public class Player : MonoBehaviour
{
  public StateType CurrentState;
  public StateType LastState; 
}

public enum StateType
{
  Attacking,
  Resting,
  Dead,
}
#

@calm ocean It doesn't seem like a ScriptableObject is what you want here - is there... data related to the actions that you need? Animations, graphics, textures, sounds, etc? It seems like you're building a FSM with ScriptableObjects which... I suppose that's possible? But I'd do it "by hand" and just use a simple enum if my assumptions are right and that you're just doing a simple-ish finite state machine

calm ocean
#

I have a scriptable objects game state. It was previously an enum but that got unwieldy

misty glade
#

Hm.. so.. best approach for FSM in Unity is a few patterns put together.. A "business logic" POCO (or a MonoBehaviour) that manages the logic for state changes, a enum for the state itself, and scriptable objects that contain the data relevant to the states

#

I tend to use scriptable objects purely as data containers and don't put any logic in them.. you can, but.. i just don't. 🙂

calm ocean
#

I guess it depends on the size of the FSM. The issue I have with enum state is that there are a bunch of switch cases scattered throughout the code base, and every time you add a new state, you got to hunt down all the times there are switch cases.

#

Anyway, that's beside the point, I guess there's no way of limiting the type to a specific implementation of a serialized field in the parent class?

misty glade
#

Like, the kind of logic I put in them is super lightweight lookup type stuff -

#

So.. like I mentioned, I think you should centralize all your state changing logic in a single class to orchestrate it.. it'll do things like return a list of valid states that you could move to, get the current state, even publish events on state change that all your UI could subscribe to if appropriate (and you want to make it a singleton)

calm ocean
#

Well I got all that except getting a list of valid states one could move to

misty glade
#

then the rest of your game just does stuff like

if (StateSingleton.CurrentState == Jumping) // display jumping pose..

StateSingleton.JumpEvent += HandleJumpEvent; // start a jump

HashMap<StateType> validNextStates = StateSingleton.GetValidNextStates();
if (validNextStates.Contains(StateType.Jump)) // jump button is enabled
#

I dunno - it's not for everyone and it's a little bit more boilerplate work but it makes separation of concerns a bit easier.. nothing in your game except for the state manager singleton has to deal with state - everything else just consumes the state and asks the state manager for info about it. Business logic in one place, race conditions eliminated, etc.

#

If you start having your game have the state management logic all sprinkled around the game (ie, at the interface layer) then refactoring or changing logic is going to be a real pain

woven kettle
#

hey,

is there is a performance benefit/disadvantage if I split a function into multiple smaller ones?

for example:

I've noticed that I'm using raycast a lot, and they all look similar to each other, just sometimes reacts differently when it hit an object of layer 2 ,4,8,30 .. etc

example :
original

// all adds up to be about 150 lines
 RayCastHit hit;
if (Physics.Raycast(source, forward, out hit, maxRange, ~layers))
{
   if(hit.transform.gameObject.layer.value == 2){ // do stuff  }
   if(hit.transform.gameObject.layer.value == 4){ // do stuff  }
   if(hit.transform.gameObject.layer.value == 8){ // do stuff  }
   if(hit.transform.gameObject.layer.value == 30){ // do stuff  }
   else{ // do stuff }
}

what I'm thinking of is to do something like that.

public RaycastHit StartRaycast(Vector3 source, Vector3  forward, float maxRange, LayerMasks ~layers)
{
    RayCastHit hit;
   if (Physics.Raycast(source, forward, out hit, maxRange, ~layers)) return hit;

}

public void ifLayer2(){// do stuff}
public void ifLayer4(){// do stuff}
public void ifLayer8(){// do stuff}
public void ifLayer30(){// do stuff}

#

am I overloading the system or wasting the resources if I split the raycast into separated functions? (that way i could swap any function I want with another without having to re-write the whole raycast instance)

deep peak
#

no

#

but you'll lose 0.0000000000000000000000000001 ms

wary swift
#

I mean.. yes it does matter if you put code into methods
It's called call overhead
But it's usually not an issue

woven kettle
#

if the issue you are talking about is 0.0000000000000000000000000001 ms then I'm ok with that.

but Im building this for android devices, and I thought why do i need to rewrite the whole raycast script just to change a small tiny thing ?

#

unless ofc 0.0000000000000000000000000001 ms issue is a problem to android devices.

deep peak
#

you can afford to lose some for readability and maintanability

#

if you remove an unused and empty Update() method from a random component, you already freed up 20x times the performance you lost

woven kettle
#

I'll double check the update methods when I start to reoptimize everything, but as far as i know I usually add if(!foo)return; on all update functions

wary swift
#

You're only hindering your program more by doing that (if the compiler doesn't save you from yourself here)

real talon
#

Personally I would just make the game, and do a few passes of optimization at the end on the biggest problems the profiler gives me.
That would be more efficient then doing it this way.

woven kettle
feral oriole
#

hello guys, I have a master script NOT associated with any gameobject in the hierarchy, which contains the classes used in my game. Is there any way I can point a GameObject field inside that script to a prefab?

wary swift
woven kettle
wary swift
#

You could try removing the script altogether or disabling it when it's not owned by the player

woven kettle
misty glade
# feral oriole hello guys, I have a master script NOT associated with any gameobject in the hie...

Not really - if there's a script that's not tied to a gameobject then .. for all intents and purposes it doesn't exist, and you can't assign members to it. What are you trying to achieve? How does your script that isn't associated with any gameobject being created? If you're doing it run-time (by instantiating it as a component and assigning it to another gameobject) then you could write an Initialize method that takes a prefab or instance of a prefab and assigns it to a member of the script

regal olive
#

there is a nave mesh on the area he is on and the arena

#

it works fine over a local network, but once it's remote the thing doesn't port him

wintry wind
#

Hi, when I shoot my projectiles on FIxed Update while the player is moving, what happens is when physics updates, the player has moved from the position where the shot came from (projectile created during FixedUpdate, Physics Update after before render). Because the player can move at very high speeds (1000m/s) this looks very strange . Is there a way to run code immediatly after Unity processes physics?

final steeple
#

The issue sounds like you want polymorphic serialization but Unity's serializer doesn't have support for that

timber flame
#

Do you think how city building games or strategy games keep stats/attributes?
A list of generic stats? So all types have the same structure.
or separate classes for each type with specific attributes/fields.
In the first approach, I have to define key/value stats for each instance
In the second approach, I only set values but also, I have to define different stat panel (UI) for each type while in the first approach, there is just one stat panel because it can iterate over the stat list

wintry wind
#

And I was only adding velocity on start, so it was starting to move a frame later

undone coral
calm ocean
native nebula
sly grove
#

neither advanced nor unity related

regal olive
#

greetings praetor, do you have any experience with navmesh Warp?

undone coral
#

for example

interface IHasTooltip {
  string name;
  string description;
}
#

can be added to many things - things you can mouse over, things that you can't... etc. etc.

#

sometimes this is done by using a dictionary of enum values ("list of attributes")

#

that are used as variables

#

in the more robust world it is coded in a scripting language (like lua) or the game stack looks exactly the same as the program stack (all your rules are in c#)

#

that is hard

timber flame
# undone coral it really depends. if you're working with a pre-existing game; or, the game logi...
//The second approach (separate UI/presenter class for each type)
public class BuildingTypeAPresenter:IBuildingPresenter{
    private BuildingTypeAStatPanel _statPanel;
    public void Show(int id){
        // find building by id
       _statPanel.Render(attributesA); // range, speed
    }
}
public class BuildingTypeBPresenter:IBuildingPresenter{
    private BuildingTypeBStatPanel _statPanel;
    public void Show(int id){
       // find building by id
       _statPanel.Render(attributesB); // count, ...
    }
}
public class BuildingController:MonoBehaviour{
     private Dictionary<BuildingType,IBuildingPresenter> _presenters;
     public void Show(int id, BuildingType type){
       _presenters[type].Show(id);
     }
}
#

In my mind, there are ONLY three ways to handle it.
1- Keep all atributes in one key/value list
2- separate data structure for each type
3- keep all fields in one structure (0 value for none)

#

Do you think how they have stored these buildings? stats

#

@undone coral Thanks, you have mentioned the first approach, it is really flexible and can ease when accessing data or showing UI (just one class to present) but I have to define key/value for each building/item in db/scriptableobject instead of only values

#

Maybe, I can have both worlds.
Define separate classes for each type and also fill stat list inside each type.

public class Building{
   protected Dictionary<string,int> _stats; // or enum instead of string
   public IReadOnlyDictionary<string,int> Stats => _stats;
}
public class BuildingA:Building{
  public int Attribute1Value;
  public int Attribute2Value;
  public int Attribute3Value;

  public BuildingA(){
    _stats.Add("Attribute1",Attribute1Value);
    _stats.Add("Attribute2",Attribute2Value);
    //...
  }

wintry wind
#

I think it depends how variable it will be. I don’t think there’s so much attribute variability in those kinds of games

#

I would use scriptable objects with each stat as a different attribute

#

And then create a attribute iterator when you want to show things in the UI (could use reflection or something more static)

#

In those kinds of games you spend a lot of time tweaking values so making them easier to tweak would be a priority for me

magic skiff
#

Has anyone ever used the recording/playback function at runtime?

What I'm trying to do is similar to functions like POTG in Overwatch.
I want to save + - n seconds as an video from a specific trigger
The difference with the POTG system is that it needs reverse play (for rewind time directing)

Unity's basic Record package does not seem to be able to runtime.

can someone share a good experience about external package or asset?

sly grove
#

you will almost certainly need to build something bespoke

novel plinth
# magic skiff Has anyone ever used the recording/playback function at runtime? What I'm tryin...

Unity's basic Record package does not seem to be able to runtime. sounds like a bad idea... Any games would not use such method for a replay... at least this simple 2d game did it properly https://www.raywenderlich.com/7728186-creating-a-replay-system-in-unity

raywenderlich.com

A replay system is a great way to let players relive their best (or worst) moments of gameplay, improve their strategy, and more! In this tutorial, you’ll build a simple state-based replay system and learn about how replay systems work.

solar hawk
#

I have a problem
in my code
i have this function
in my player target script
and it has an if statement
which never seems to go off
any help would be apreciated
my player target script is:
https://paste-bin.xyz/73442
Player Target Script - pastebin -for Sharing Code and Text.
Player Target Script - pastebin Paste can store text, source code or sensitive data for a set period of time.
Player Target Script - pastebin -for Sharing Code and Text.
my movement script is:
https://paste-bin.xyz/73443

i am refering to line 27
Player Target Script - pastebin -for Sharing Code and Text.
Player Target Script - pastebin Paste can store text, source code or sensitive data for a set period of time.
Player Target Script - pastebin -for Sharing Code and Text.
Movement Script - pastebin -for Sharing Code and Text.
Movement Script - pastebin Paste can store text, source code or sensitive data for a set period of time.
Movement Script - pastebin -for Sharing Code and Text.
I used debug.log and health does decrease and does get below 0 so idk
I would appreciate any help

Player Target Script - pastebin Paste can store text, source code or sensitive data for a set period of time.

Movement Script - pastebin Paste can store text, source code or sensitive data for a set period of time.

turbid tinsel
#

Where do you call that function?

#

TakeDamage

#

put a debug.log inside TakeDamage before the if, and put it inside the if as well

#

see if any go off

#

if none go off, you must be changing your health somewhere else

solar hawk
#

i call it in my hotbar script

#

sorry

#

lemme grab it

#

here

#

@turbid tinsel

#

i have a debug log infront of the if and it works

#

so idk

#

this is rlly weird

turbid tinsel
#

why don't you do playerTarget.TakeDamage(damage); on line 152? shouldn't change much but it's weird

#

ah

solar hawk
#

what?

turbid tinsel
#

PlayerTarget inherits from target, yes?

solar hawk
#

yea?

turbid tinsel
#

you're calling it twice on the playerTarget

#

idk what it changes, tho

solar hawk
#

wtf really

turbid tinsel
#

yea

solar hawk
#

where

#

which script

turbid tinsel
#

this

#

returns the same thing

#

its the same object

sly grove
#

PlayerTarget : NetworkBehaviour

turbid tinsel
#

and you call the same function on both

sly grove
#

I don't think so

turbid tinsel
#

o

#

right xd

solar hawk
#

nah my target script is dif

turbid tinsel
#

idk then

solar hawk
#

lol

#

thx anyway

sly grove
turbid tinsel
#

o yea

sly grove
#

And it works in what way? What does it print?

#

And what about one inside the if?

turbid tinsel
#

the one in the takedamage function

#

before the if

solar hawk
solar hawk
turbid tinsel
#

yea

solar hawk
#

it goes below 0

sly grove
solar hawk
#

and it seems fine

turbid tinsel
#

and the if doesnt go off?

sly grove
#

Ok and a log inside the if?

solar hawk
#

nothing

sly grove
#

show the code with the logs

turbid tinsel
#

double click the if

solar hawk
#

the if statement isnt going off

turbid tinsel
#

debug*

solar hawk
turbid tinsel
#

the debug log in the editor, click it and check where it goes

sly grove
solar hawk
#

yea

sly grove
#

let's see where you added logs

solar hawk
#

i did

#

do u want the console?

sly grove
#

and what they printed exactyl

#

I want to see the code with the logs in it and what the result is in the console, yes

solar hawk
#

ok cool

#

one sc

#

sec

#

there

#

@sly grove

sly grove
#

and the code?

solar hawk
#

i gave all the code above

#

lemme grab it hold on

sly grove
# solar hawk i gave all the code above

No, you gave the code without any log statements in it. I want to see what the code looked like when you ran the game and got that log output you just shared

solar hawk
#

wdym

#

how do i do that?

sly grove
#

I'm really not sure how to be more clear

turbid tinsel
#

the modified code

#

with the Debug.Log commands

solar hawk
#

i havnt change it tho

turbid tinsel
#

PlayerTarget

solar hawk
#

they were already there

#

from previous debugging

#

?

turbid tinsel
#

then how are the Debug.Logs popping up

sly grove
#

I don't see any log statements here

solar hawk
#

bc thats the target script

sly grove
#

it's PlayerTarget

solar hawk
#

not the player target script

turbid tinsel
#

no, that's playerTarget

sly grove
solar hawk
sly grove
#

yes...

#

that's the same link I gave

#

and there's no log statements in there

solar hawk
#

for me there are

turbid tinsel
solar hawk
#

yea

turbid tinsel
#

then send us the new one

solar hawk
#

its that

turbid tinsel
#

yea

solar hawk
#

here

turbid tinsel
#

send us the new one

#

with debug logs in there

solar hawk
#
using System.Collections.Generic;
using UnityEngine;
using Mirror;

public class PlayerTarget : NetworkBehaviour
{
    [SyncVar]
    public float health = 50f;

    public GameObject playerModel;
    PlayerMovement pm = null;

    [SyncVar]
    public bool isAlive = true;


    private void Start()
    {
        pm = GetComponent<PlayerMovement>();
    }


    public void TakeDamage(float amount)
    {
        health -= amount;
        Debug.Log(health + " = Health");
        if (health <= 0f)
        {
            Die();
        }
    }


    [Command]
    void Die()
    {
        
        isAlive = false;
        //gameObject.SetActive(false);
        playerModel.SetActive(false);
        Debug.Log(gameObject.GetInstanceID().ToString() + " has died!");

        pm.GetHealth(isAlive);
    }

    
    

}
turbid tinsel
#

thank you

sly grove
#

We are trying to verify that the if statement isn't working. It's incumbent you add a log inside the if statment

solar hawk
#

bc there is a log in Die()

#

ok fine

#

hold on

sly grove
#

which may be part of the problem

turbid tinsel
#

change

health -= amount;
        Debug.Log(health + " = Health");
        if (health <= 0f)
        {
            Die();
        }

to

health -= amount;
        Debug.Log(health + " = Health");
        if (health <= 0f)
        {
            Debug.Log(health + " = Inside if Health");
            Die();
        }

sly grove
#

but you complained about the if itself

#

so start there

turbid tinsel
sly grove
#

My guess is this object doesn't have a proper NetworkIdentity or something like that

turbid tinsel
#

although that'd be terrifying

solar hawk
#

ok so

#

the if statement works

#

i got a log

sly grove
#

yep

#

not surprising.

solar hawk
#
        {
            Debug.Log("If statement is working!!!");
            Die();
        }```
#

just added that

#

so

#

why isnt the die thing working then?

sly grove
#

So it's an issue with [Command]

solar hawk
#

thats rlly weird

sly grove
#

it's not that weird

solar hawk
#

it does

#

i have this under my main player prefab

#

with all my other scripts

sly grove
#

and does the client have authority over the object

solar hawk
#

yes

#

90% sure

sly grove
#

basically I believe Command needs to run from whichever host has authority on the object

solar hawk
#

how do i check

sly grove
#

I'd double check all that

solar hawk
#

hold on

sly grove
#

I've never really used Mirror but can't you check all that stuff on the NetworkIdentity? Like who has authority on the object etc

solar hawk
#

yea

#

it does have authority

#

so

#

idk the problem

#

would it work if i removed the [Command]

turbid tinsel
#

likely

#

you can check

sly grove
#

depending on your definition of "work" 😛

#

the code will run

#

definitely

solar hawk
#

i just want it to show on the other client

sly grove
#

will it work properly across the network or whatever? Idk

solar hawk
#

ok

#

thanks

#

both of u

#

tysm

sly grove
solar hawk
#

ok thanks

#

sorry if i was a pain to help

#

lol

chilly nymph
#

What pattern would you guys go with for a 2D game (point and click) sort of like civ but without 3D elements.

timber flame
timber flame
feral oriole
# misty glade Not really - if there's a script that's not tied to a gameobject then .. for all...

Thanks for the reply. I have a master script in my project folder with a namespace, I reference it from the other scripts by the namespace. I'm trying to assign a prefab to it, instead of doing it, for example, from the player, every time I want to instantiate it, just like you suggested. From what I understand, it's almost impossible to do, though... I might have to reword my game architecture, maybe including this master script in one GameObject in the scene

rapid flume
#

how to limit air control?

hard lily
rapid flume
hard lily
#

Let's say you want the air control to be 50% of grounded speed. Just multiply it by 0.5f.

rapid flume
#

I have a enum

high mirage
hard lily
#

Now you need a way to keep track of what is regular speed, like separate your moveSpeed into 2 fields: moveSpeed & currentMoveSpeed

#

That way when you are grounded again you can set currentMoveSpeed to moveSpeed

compact ingot
#

maybe its just detected through a checksum of some sort

rapid flume
formal gale
#

Hi. Some time ago i stumbled across weird issue with updating gradient editor in custom inspectors. I wasn't able to resolve the issue. So if someone would like to see and maybe help, feel free to check out the thread on unity forum: https://forum.unity.com/threads/gradient-propertyfield-not-updating-in-custom-inspector.1319796/

hard lily
#

And I see that you already have a way to track what is your regular speed so you can disregard the example I gave you about "currentMoveSpeed" and etc.

rapid flume
hard lily
#

You can even simply it further by just having a airSpeed field instead

rapid flume
#

can you fix my code and send me?

hard lily
#

I can't fix your code but I can help you get there, line 77 and 78 is wrong. Again, I suggested you use fields such as currentMoveSpeed because I didn't know you already had fields to keep track of the base speed

rapid flume
hard lily
#

Does walking and sprinting work? Do they have different speeds when you try them?

#

If they do, you can do the same thing for when you are in the air, just use an "airSpeed" variable instead

#
// Jumping
else if (rb.velocity.y > 0)
{
    state = MovementState.jumping;
    moveSpeed = airSpeed; 
}

That should work, right?

rapid flume
#

but then your air speed will be the same when you jump while walking and also jump while running

hard lily
#

Then the example I gave you first should do the trick, provided you only do it once

#

Because you run that method every frame, that would keep decreasing your speed by half each time. To circumvent this you can just check if the state is already the one you are going to change to, if it is then you can skip it. An example using a guard clause:

else if (rb.velocity.y > 0)
{
    if(state == MovementState.jumping) { return; }
    state = MovementState.jumping;
    moveSpeed = currentSpeed / 2; 
}
wintry wind
#

Also you should check for air by using a ray cast to check if you are on the ground. Using y will give janky behavior on slopes, when falling, etc

rapid flume
rapid flume
#

using my own tiny brain thing

#

if you dont have enough velocity your air speed will be very small too thx bro

rapid flume
#

this is the code I used, I know it can be shortend but who cares for clean code(everyone does except me)

spare elbow
#

im using google admob but when the user earns a reward through watching an ad, i get an error when im trying to reward the user with the reward

#
    {
        string type = args.Type;
        double amount = args.Amount;
        MonoBehaviour.print(
            "HandleRewardedAdRewarded event received for "
                        + amount.ToString() + " " + type);

        if (type == "revive")
        {
            Level2Referencer.Instance.deathTimerManager.Revive();
            Level2Referencer.Instance.manager.Revive();

            StatSaveManager.Instance.AdWatched();
            StatSaveManager.Instance.Save();
        }
        

    }```
#

the error is: UnityException: get_gameObject can only be called from the main thread.

#

The error points to this:

#
    {
        gameObject.SetActive(false);
    }```
#

this is on android btw

tender light
spare elbow
#

could you link me to some documentation about it or something

#

can i also just set a bool about invoking an action

#

like: public bool invokeAction = false;

#

and then in the update:

#
{
  Action();
  invokeAction = false;
}```
#

i think this is what you are talking about right?

tender light
high lake
#

Hi, Im trying to simulate rays of light passing through surfaces. I currently have a working system using raycasts and mesh colliders. However, with curved surfaces, mesh colliders are innaccurate so I want to use equations for curved surfaces (e.g x^2 + y^2 + z = 0). However I have no idea how to calculate the intersect between a curved surface and a 3D line. Another problem is that I want to be able to rotate the surface and move the surface similar to how you can rotate objects using Unity's gizmos, but I have no idea on the maths behind this problem. Does anyone know how to do this / can point me to some resources which I can read up on.

sly grove
fringe root
#

Bumping my problem. So... Im trying to create a recoil system for my FPS game.
I can sway the gun with the mouse, i can apply a kickback to z axis, everything is fine but getting the rotational recoil right. Would appreciate some help!
https://hatebin.com/aqsasflcuv

#

I have tried using lerp, slerp and even the smoothlerp function i use in my adc sistem

regal olive
#

https://i.imgur.com/hZRtgjc.png
Is this normal? I am experiencing this since upgrading to Unity 2021.3.7f1 . Before that the Project was on Version 2020.3.36f1 and nothing unsual was there. This is just Resources.Load. Any Idea from what this could come or how to fix it? Oh and it is on Android

gray pulsar
fringe root
#

You are Right

gray pulsar
# fringe root Bumping my problem. So... Im trying to create a recoil system for my FPS game. I...

that said, my guess looking at your code is that you're seeing instability in the rotation. Sometimes it just freaks out and rotates weirdly. If that's true, it would be because you're both reading from and writing to the rotation using euler angles. The value that euler angles returns to you is not necessarily stable from frame to frame. It can flip by 360 from one frame to the next (ie 90 => -270)

#

so if you try to lerp or smoothdamp or w/e on an euler angle that you're not tracking yourself

fringe root
#

uhm.. i didnt know that. that helps already

gray pulsar
#

you could get some gnarly results

fringe root
#

that indeed happened

#

one other problem is that my targetWeaponRotation goes all the way to 360,0,0

#

and doesnt really come back

#

so its not lerping back to vector3.zero

#

and what happens is that my gun starts to point at the sky and doesnt come back. that happens very slowly tho

gray pulsar
#

you should either:

  1. store what you think the euler angles should be in your own variable rather than reading it from the transform and overwrite whatever the transform has every frame
    or
  2. do everything in quaternions rather than euler angles
fringe root
#

uhm...

#

i guess option one shoulds decent enough

gray pulsar
#

a separate issue is that Vector3.SmoothDamp and Vector3.Lerp is not designed for angles, so they don't wrap around

fringe root
#

Slerp?

gray pulsar
#

Quaternion.Slerp is really waht you want

#

but you need to pass quaternions into it, not euler angles

#

doing everything in quaternions is really a much better option than dealing with euler angles

#

like, are you just trying to recoil around one axis? Quaternion.AngleAxis

fringe root
#

but taking into consideration that i already have a bunch of vector3, i can just convert that into Quaternion.Euler and then pass it to Quaternion.Slerp?

#

It's both axis unfortunately

gray pulsar
#

you can, but you have to be calculating the Vector3s in a way that is appropriate for euler angles

#

ie it has to be treating them as angles, not as points in space or as directions

fringe root
#

math, not even once kids

#

nah im joking. I guess i never really thought of it that way

gray pulsar
#

yeah, unity overloads the Vector3 type to mean a lot of different things. It would be nice if there was a bit of type safety between its actual physical meanings rather than just "oh, a vector is a collection of 3 floats, duh"

fringe root
#

ok, just from changing to this newRecoilWeaponRotation = Quaternion.Slerp(newRecoilWeaponRotation, Quaternion.Euler(targetRecoilWeaponRotation), snappiness);

#

it already comes back, very slowly, but it does

#

if you dont mind me abusing of your good will sir, next step for me would be getting this recoil angle and applying to the raycast

#

but if i just do (origin - destination) + angle . normalized it gives me very weird results

#

like not even close to the direction it should be facing

gray pulsar
gray pulsar
#

trying to wrap my head around what you're asking

#

you have a raycast for where the gun would fire if unrotated, and you want to apply the rotation to that direction?

fringe root
#

yes

#
public void FireFullAuto()
    {
        if (bullets > 0 && canShoot)
        {
            if (Time.time > lastShotTime + fireRate)
            {
                IncreaseRecoil();
                bullets--;
                lastShotTime = Time.time;
                muzzleFlash.Play();
                RaycastHit hit;
                if (Physics.Raycast(cameraTransform.position, cameraTransform.forward, out hit, Mathf.Infinity))
                {
                    Vector3 direction = ((hit.point - weaponPivot.GetChild(0).transform.position) + newRecoilWeaponRotation.eulerAngles).normalized;

                    if (Physics.Raycast(weaponPivot.GetChild(0).transform.position, direction, out hit, Mathf.Infinity))
                    {
                        GameObject go = Instantiate(currentGun.bulletHolePrefab, hit.point, Quaternion.LookRotation(hit.normal));
                        go.transform.position += hit.normal / 1000;

                        if (hit.transform.CompareTag("Enemy"))
                        {
                            Debug.Log("hit enemy");
                        }
                    }
                }
            }
            
        }
        else StartCoroutine(Reload(reloadTime));
gray pulsar
#

rotatedVector = quaterion * unrotatedVector

#

direction + eulerAngles is the same kind of nonsense I was talking about before, mixing up two different meanings of Vector3

"up" as a direction is (0, 1, 0), but up as eulerAngles is like (90, 0, 0). Adding those two things together gives you (90, 1, 0), which is.... very much not the value you were probably looking for

fringe root
#

i see

#

changed it to Vector3 direction = newRecoilWeaponRotation * (hit.point - weaponPivot.GetChild(0).transform.position).normalized;

#

and it has a pretty decent result to be honest

fringe root
#

alright sir, you've given me a better lesson in 10 minutes than many hours of classes in college

#

thank you so much. i'll make sure to treat my vector3s better after this

gray pulsar
#

you're welcome! glad to help

#

this conversation got me thinking about whether I can implement a wrapper for them myself so you actually get type safety

fringe root
#

that would indeed be very useful

wintry wind
#

<rant>I hate Quaternions...</rant>

misty glade
#

@fringe root Unsolicited opinion - your code would be a lot cleaner if you strived to adopt the "no else" and "only one indent" approach from object calisthenics. Because I'm a terrible person, I refactored your code to show what it might look like. https://pastebin.com/tCKLGYZZ

wintry wind
#

Quaternion.RotateTowards(_baseRotation, wantedRotation, maxAngle) => if maxAngle = 0, shouldn't this return _baseRotation ?

misty glade
#

(i didn't analyize the two-raycast-check thing, i don't quite know what it does, i just reformatted the code a tiny bit)

misty glade
#

(think of the case where you are aimed in the same direction but doing a barrel roll)

wintry wind
#

It currentlies go completely crazy (target is the result of that expression): Base: (0.00, 0.00, 0.00) | Wanted: (359.88, 0.12, 89.96) | Target: (359.99, 0.04, 20.00)

#

and each frame is different

#

This moved by 20 degrees, so it basically ignored my max angle

misty glade
#

what are you using to get your quats for Quaternion.RotateTowards?

wintry wind
#

Quaternion wantedRotation = Quaternion.LookRotation(rotatingTransform.InverseTransformDirection((targetPosition - rotatingTransform.position).normalized), rotatingTransform.up);

misty glade
#

and _baserotation?

wintry wind
#

it's localRotation at Start, so 0,0,0

misty glade
#

hm, weird.. probably shouldn't matter honestly if the 3rd parameter is 0

#

maybe there's undocumented/unpredictable behaviour if the parameter is 0.. try setting it to something small like 1

#

(i believe that's degrees per second, but i forget if it's in degrees or radians or whatever)

#

degrees

wintry wind
#

It should be degrees at least according to the example in the documentation

#

I think I’ve done something similar in the past, I guess I’ll search for it

#

Quaternions never work 😂

split folio
#

@fringe rootthats one hell of a ladder

wintry wind
#

How do I clamp a rotation to a given amount? I don’t want my transform to rotate more than X degrees (local rotation)

split folio
#

first get the local rotation of the transform
then call the clamp function and set axis float value to the clamped value
now set the new rotation with the new clamped value

wintry wind
#

There is no clamp function for quaternions

split folio
#

no but you can get the individual values still and clamp those

sly grove
#
float rotation = 0;

void AddRotation(float amount) {
  rotation += amount;
  rotation = Mathf.Clamp(amount, min, max);
  transform.localRotation = Quaternion.Euler(rotation, 0, 0);
}```
#

This way is ideal because you don't need to deal with reading euler angles from the Transform, which are very finicky and sometimes give you the negative version etc.

fringe root
split folio
fringe root
#

Also just realized how dumb it was to have two identical functions called FireSingle and FireFullAuto, when they are already called in diferent conditions

#

🤦‍♂️

wispy terrace
#

I installed the Navigation 1.0.0-exp.4 package which includes the NavMeshSurface component, but I can't create a variable in a script to store the component. Any ideas as to why?

misty glade
#

using UnityEngine.AI.Navigation;

wispy terrace
#

These are all the classes it gives me, and I think NavMeshLink is part of the Navigation package so, I guess the package has been imported

misty glade
#

sorry, not unityengine, but Unity

#

using Unity.AI.Navigation;

wispy terrace
buoyant leaf
#

having trouble debugging from vscode

#

gave me this error```[Window Title]
Visual Studio Code

[Content]
error while processing request 'launch' (exception: Object reference not set to an instance of an object. at UnityDebug.UnityDebugSession.CleanPath(String pathToEditorInstanceJson) in D:\prog\external\vscode-unity-debug\UnityDebug\UnityDebugSession.cs:line 339
at UnityDebug.UnityDebugSession.Attach(Response response, Object args) in D:\prog\external\vscode-unity-debug\UnityDebug\UnityDebugSession.cs:line 310
at CallSite.Target(Closure , CallSite , UnityDebugSession , Response , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid3[T0,T1,T2](CallSite site, T0 arg0, T1 arg1, T2 arg2)
at UnityDebug.UnityDebugSession.Launch(Response response, Object args) in D:\prog\external\vscode-unity-debug\UnityDebug\UnityDebugSession.cs:line 257
at CallSite.Target(Closure , CallSite , DebugSession , Response , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid3[T0,T1,T2](CallSite site, T0 arg0, T1 arg1, T2 arg2)
at VSCodeDebug.DebugSession.DispatchRequest(String command, Object args, Response response) in D:\prog\external\vscode-unity-debug\MonoDebug\src\DebugSession.cs:line 401)

[Open 'launch.json'] [Cancel]```

wintry wind
#
        _targetRotation = wantedRotation;
        rotatingTransform.rotation *= _targetRotation;```
#

now, I want to make sure the rotatingTransform.localrotation is not above a max angle or else turrets would be super janky (like rotating inwards to the player)

#

I can't seem to find a way

#
    private Quaternion ClampRotation(Quaternion rotation, float maxAngle)
    {
        Vector3 angles = rotation.eulerAngles;
        angles.x = ClampAngle(angles.x, maxAngle);
        angles.y = ClampAngle(angles.y, maxAngle);
        angles.z = 0;
        return Quaternion.Euler(angles);
    }

    private float ClampAngle(float angle, float max)
    {
        if (angle < 180f)
        {
            return Mathf.Clamp(angle, 0f, max);
        }
        else
        {
            return Mathf.Clamp(angle, 360f - max, 360);
        }
    }```
#

I tried this but it starts randomly rotating

#

I just found out in previous projects i basically used IK components but seems like an overkill in this situation

#

This seems like a pretty standard use case, I don't understand why it is so difficult lol

undone coral
#

i read what you are trying to do and it didn't make sense to me

#

it's difficult to express in words what your hierarchy should be

#

and then reading this stuff it's tough because you don't use var

#

it gets really verbose

#

so it's a code style thing too

wintry wind
#

What I want is:

undone coral
#

you should never ask the turret to rotate to an invalid target rotation

wintry wind
#

I want to rotate this turret towards a target position. But as you can see in the image, the turret can't rotate X more than 90 degrees or else it will hit the control tower above

undone coral
#
// pseudocode
// get the euler angles needed to point at the target
// then, clamp those angles.
#

the clamp ranges you need are specific to the hierarchy of the turret

#

you probably made it challenging to decompose the rotation of some simple vector "looking at" the target into the hierarchy you actually have

sly grove
#

I'm showing you how to do it - try to avoid reading back eulerAngles from the Transform because that gets you into trouble

wintry wind
#

because I don't know how to reach the float

sly grove
#

wdym "reach" it

wintry wind
#

How can I find the float.

sly grove
#

??

wintry wind
#

My code is super simple withoput clamping, it's just this:
Vector3 direction = (targetPosition - gimbalTransform.position).normalized;
Quaternion wantedRotation = Quaternion.FromToRotation(gimbalTransform.forward, clampedDirection);
gimbalTransform.rotation *= wantedRotation ;

sly grove
#

I understand that

#

but you can't do it that way if you want to clamp

#

You'll need to define your own rotation variable(s) and drive the rotation from there

wintry wind
#

That is what I don't know how to do it. Should I use Vector3.SignedAngles to discover those variables?

sly grove
#

"discover" them?

#

No like I said

#

define your own variables

#

drive the rotation from those variables

#

as per my example code

wintry wind
#

I don't understand how it fits my use case. How can I use your code to rotate to a specific point?

#

This is for AI, not player input

sly grove
#

determine the angle that would be required to aim at that point

#

then set the angle to that (but clamped)

wintry wind
#

that's what I called discovering them

sly grove
#

Ok yes, you could use Vector3.SignedAngle

#

basically comparing the turret's normal "forward" direction to the required direction

#

to find the correct number to use as the angle

#

then you clamp it

wintry wind
#

k, thanks

#

I'll try with signed angle

calm ocean
#

Currently, I have a scriptable object representing a player action. It contains the relevant stats (like the attack action has attack damage and range), and it can also be used to execute the action. In the game, the scriptable object can return a button so that it can display to the user what actions they want to pick. The issue I am facing now is that each of these scriptable objects require a button prefab for that method to instantiate. So if I have 100 of these scriptable objects, I would have to assign the prefab 100 times. I was wondering if there is a way for the method to know about the button prefab without dragging it in via the inspector. I was thinking of a making a factory singleton scriptable object that takes in the button prefab, and has a static method Create(), that returns the instantiated prefab. Is this a terrible idea and I should just have a button prefab field in that my player action scriptable object?

#

Or is there a better way?

sly grove
#

Assign it a delegate from the SO as you instantiate it

calm ocean
sly grove
# calm ocean So drag and drop the button prefab into the inspector window?

something like:

public class MyButtonScript : MonoBehaviour {
  Action theAction;
  TMP_Text buttonText;

  // Call this right after instantiating
  public void Init(String actionName, Action buttonAction) {
    theAction = buttonAction;
    buttonText.text = actionName;
  }

  // Assign this one as the button on click in the inspector inside the prefab
  public void OnButtonClick() {
    theAction?.Invoke();
  }
}```
calm ocean
#

Yeah I have something like that

#

I was just wondering how to get the player action SO to reference this

#

Because all of the player actions ideally should have the same button prefab, I shouldn't have the ability to drag and drop a different button prefab for two different player actions.

sly grove
#

So then you'd have another script doing something like this:

public class SomeOtherScript {
  public MyButtonScript buttonPrefab;

  public void InitActions(List<MyScriptableObject> sos) {
    foreach (var so in sos) {
      MyButtonScript instance = Instantiate(buttonPrefab);
      instance.Init(so.ActionName, so.ActionMethod);
    }
  }
}```
calm ocean
#

OOOOhhhh, okay

#

But I would have to expose some stuff from the SO

#

But I get the idea

#

Thanks

chilly nymph
#

What pattern would you guys go with for a 2D game (point and click) sort of like civ but without 3D elements.

sly grove
chilly nymph
#

No, the actual design pattern.

sly grove
#

Although honestly Unity's "cell index" layout for hex grids is a bit nonsensical to me

#

What like MVC?

chilly nymph
#

I'm leaning towards MVC

sly grove
#

Idk I think design patterns like that are generally over-engineered and not really great for realtime applications

#

Definitely I would separate the game model (board state etc) from the GameObject world

misty glade
#

I'm an MVC enjoyer, I think it's good.

deep peak
#

games are usually too complex for well known application design patterns, you will break you design at some point anyway

misty glade
#

models can be shared/serialized/networked easily, app has a layer of singletons as the controller and the game objects/ui/input collectors as the "viewer"

chilly nymph
sly grove
#

you definitely want a well defined model for serialization/networking etc... he's right about that

#

but the distinction between view and controller doesn't need to be so well defined

chilly nymph
#

I understand the fundementals, just looking for suggestions.

misty glade
#

i mean, you should just have a single Model.cs class with 20,000 lines of code and pass a pointer to it around, right? /s

#

🙂

chilly nymph
#

This is advanced talk right?

misty glade
#

@chilly nymphFor games and game dev in general, I suggest not overengineering to start and literally proof-of-concept-pyramid your way to success.. ie, build a tiny POC then scrap it and start anew when it's too spaghet - keeping the relevant/useful logic and dropping it into a new project.

chilly nymph
#

That's not what I'm really asking...

misty glade
#

What are you asking, then? 😛

chilly nymph
#

I'm a 10th year SE looking for suggestions on what patterns I should use.

misty glade
chilly nymph
#

I'm leaning on MVVC because it solves all my states as well as systems.

deep peak
#

there no good answer to this KEKW really, we've been all there when the best patterns failed

chilly nymph
#

But if you guys can suggest something else I would be open too it.

chilly nymph
sly grove
#

Basically GameObjects and their Components are the presentation layer

chilly nymph
#

I'm looking for advice.

sly grove
#

I can read, I'm giving advice

#

literally gicving you advice

chilly nymph
#

Have you ever asked a question?

sly grove
chilly nymph
#

Advice doesn't mean I'm not open to others ideas.

sly grove
#

great, and right after that I gave some suggestions

chilly nymph
#

Then why make that comment?

woven kettle
#

hey,

I have 2 list of Property info

 public List<PropertyInfo> oldVarList = new List<PropertyInfo>();
 public List<PropertyInfo> newVarList = new List<PropertyInfo>();

how to look for every value in "oldVarList" and see if any variable with the same name/hash/whatever ...in newVarList and if true, try to replace the newVarList var variable value by the oldVarList var value

wary swift
#

It's up to personal preference what code design patterns you want to use
Some people like xyz and others will hate it, just do what you prefer, it's your project

chilly nymph
sly grove
#

Anyway my point is Unity already has a forced design pattern of GameObjects/Components which you have to overlay whatever you're doing on top of. So I feel it's best not to try to get too pedantic about what's a Controller and what's a View when it comes to MonoBehaviour scripts.

chilly nymph
woven kettle
chilly nymph
woven kettle
# chilly nymph It seems like there's a better way to solve your problem, what are you trying to...

Im making a new class ,lets call it "NewClass", which is inherited(based) on an older class lets call it "OldClass" which would look in code, something like this

using UnityEngine;
public class NewClass : OldClass
{

}

the "OldClass" has lots of public variables that were setup on the editor, when I made the new class I found that all those value has returned to default. (in the NewClass component only ofcourse, the OldClass component still has all the public values)

is it possible to copy the variables value of the OldClass to the new one sense they are the same?

for example if i made a new gameobject and added OldClass to it I could simply go the other OldClass gameobject, click on the 3 dots and then copy component >>> back to the new gameobject >> past Component values

chilly nymph
#

Make a factory?

woven kettle
#

I've just answered

#

factory?

#

no all what I'm trying to do is what I've just mentioned

chilly nymph
#

That is, you are trying to solve problem X, and you think solution Y would work, but instead of asking about X when you run into trouble, you ask about Y.```
#

There's a simpler way to achieve what you want @woven kettle just let us know what you are trying to do, what functionality.

#

Not what your solution is.

#

To me it sounds like you want a factory.

#

is it possible to copy the variables value of the OldClass to the new one sense they are the same?

woven kettle
#

ok its what I have said, X is Y in my issue

#

what do u even mean by factory?

chilly nymph
#

Google factory pattern.

wary swift
fresh salmon
#

You can use the MovedFrom attribute to "move the values of a serialized type to another", iirc

woven kettle
#

ok, the factory thing is not what I'm doing, I do have a new class and I wanna copy the public value I set manually on the editor via script

#

because manually takes forever even when I tried it, it didnt works because I possibly have missed something

chilly nymph
wary swift
#

Would it be an idea to use scriptable objects to store settings and read them?

chilly nymph
#

If you want to create a new class create an object and pass in the constructor or a SO ^

#

BUT not being rude but a better understanding about classes will help you here.

sly grove
#

you could certainly use them as data containers that persist outside of and between scenes but they don't persist between play sessions, you'd need to serialize the, externally for that

woven kettle
wary swift
sly grove
#

I'm drifting in and out of chat my bad haha

fresh salmon
woven kettle
#

im down for the easiest way in doing that, I asked that yesterday and many ppl said you are on ur own you have to do it manually 😄 , so I'm happy to know that I have options today 😄

chilly nymph
fresh salmon
#

No, automation

woven kettle
chilly nymph
#

You guys need to get your shit together 😄

fresh salmon
#

Factory is utility class that that constructs stuff for you, it's not relevant

deep peak
#

just do it by hand, it will take 30m, whatever, next time you wont change core components of your game

hoary pendant
chilly nymph
fresh salmon
woven kettle
chilly nymph
#

Are you saying you need to literally copy the inspector values to another component?

fresh salmon
#

Yes

#

Literally

chilly nymph
#

Copy the fkn component.

woven kettle
deep peak
#

he wants those values inside the new component

fresh salmon
#

Well you can't

chilly nymph
#

If it has the same struct you can...

fresh salmon
#

Two different classes

sly grove
#

Oh man this question still?

chilly nymph
sly grove
#

You've been working on this over a day, you could've probably copied the values manually by now

wary swift
#

You could hack your way around it with reflection, but I'm not going to go into that 😂

woven kettle
sly grove
#

Also you could try hacking the yaml scene/prefab file to change the script GUID to point at the other script and if the field names are the same it might work 😛

chilly nymph
woven kettle
fresh salmon
chilly nymph
#

OldClass != inspector component.

fresh salmon
#

A component is a class lol

chilly nymph
#

It's not a inspector element mate.

fresh salmon
#

Yes it is

woven kettle
#

i feel like u are talking about something else other than unity 😄

sly grove
#

the inspector copy component stuff doesn't work in this case - we have established that

chilly nymph
#

wtf are you talking about, a class doesn't represent a inspector component, it's a layer on top of unity.

#

A class is a object.

fresh salmon
#

MonoBehaviour : Behaviour : Component : Object

deep peak
#

dont mind them, we know your problem, there are multiple solutions, but no one going to just write it for you

chilly nymph
fresh salmon
#

Lmao

woven kettle
#

I can copy inspector values from "OldClass" to another "OldClass" ... but I cant copy the inspector values from "OldClass" to "NewClass" because they are not the same.

so my solution to that is to make a script that compares the variables with the same name and then copy the value from "OldClass" to the "NewClass" (even though the "NewClass" is inherited from "OldClass" )

#

so I have right now 2 lists of PropertyInfo ... and I'm looking for the best way to compare the variable in each

#

that is all

wary swift
#

Just iterate over them all
Who cares if it's O(n^n)
It's just editor code, performance doesn't matter

chilly nymph
#

serialize to json and be done with it.

deep peak
#

what's the problem with ```
newComponent.myStuff = oldComponent.myStuff;
newComponent.myStuff1 = oldComponent.myStuff1DiffName;
newComponent.myStuff2 = oldComponent.myStuff2;

#

why you need reflection for this

sly grove
#

well

#

depends how lazy you are I guess

#

you either write some reflection code or your tediously write out each field name

deep peak
#

that would be a whole new level of laziness

sly grove
#

software developer laziness means building crazy tools if it means you don't have to manually copy 50 numbers from column A to B 😆

fresh salmon
#

It would probably take more time using Reflection and making sure it works, than writing it all out

sly grove
#

Probably yes

#

but it also depends on how many fields we're talking about lol

fresh salmon
#

Oh please not a god object

sly grove
#

if it's 1000 fields (it's not i know) it could be faster to write the code

#

somewhere between 0 and 1000 is the sweet spot

wary swift
woven kettle
deep peak
#

with 1000 fields i would just edit the scene file, its just YAML KEKW

fresh salmon
#

It's probably faster than all solutions previously mentioned

#

Make a backup though, you definitely can corrupt the scene/project if you do something wrong

keen cloud
#

Do you guys know of a way to automate the NPC creation process? If I were to have x sprite sheets formatted the exact same way, how would I automate splitting each sheet then creating a bunch of animations

gentle trench
#

Sorry if i did not explain this well, im trying to make tthe chunk that the player is in to generate higher detail

sly grove
gentle trench
eager dust
#

Anyone can tell me why it can't find my GO? It's null... The GO is in Scene.

    [Test]
    public void ShuffleTest()
    {
        Deck deck = GameObject.Find("Deck").GetComponent<Deck>();

        //More stuff happens here
    }
sly grove
eager dust
sly grove
#

this is a unit test though right

eager dust
#

Yes

sly grove
#

I don't know how do scenes work in unit tests

#

Doesn't it load a fresh empty scene

eager dust
#

Sec. will check

#

Dangit, yes you're right

#

So I should either load the scene in the test method or find a way to create the deck GO, add the Scripts to it and populate the list with the Assets from the Assetfolder..

sly grove
#

I htink people usually use like Resources.Load for unit tests

#

to load a prefab

#

Or build the GameObjects in code manually with AddComponent etc

eager dust
#

Ah will test the Resources.Load way ty

#

Worked like a charm

#

ty! 🙂

undone coral
#

is there an aspect ratio fitter component that rescales its contents in UGUI

violet valve
quartz stratus
chilly nymph
#

I'm pooling my ui element, other than the memory allocation. Under the hood is there anything else that is processed? Does anything get dirtied if a canvas / component is off?

novel plinth
#

pooling a ui element is like the most unnecessary thing to do, unless your game consists of, well, UIs.. 🧐

#

as in 90% of your game is just.. UIs

chilly nymph
#

Would be crazy if I was making a 2D game, hey?...

#

You guys ever actually answer questions? 😄

undone coral
#

i authored it, it was simple enough

#

i meant localScale rescaling as opposed to rect or sizeDelta