#archived-code-general

1 messages ยท Page 28 of 1

main shuttle
#

Yeah, it's called BoxCast

quartz folio
#

Because packages can be updated, and it requires me to only use git flow to push updates. They also support dependencies, and are well isolated by default.
Meanwhile UnityPackages require extra work and have no features.

main shuttle
#

Or BoxCastAll in your case

misty jewel
main shuttle
#

Since you want all the gameobjects in that box, not just a single one.

hidden kindle
#

So I have a strange issue

#

For whatever reason, my enemy AI moves just fine in the player

#

But I built it and in the build version, the AI keeps starting and then stopping

#

I'll try building it again and see if there was just something wrong with that build

#

I also get these messages when trying to build

cedar pivot
#

hi i have a problem at my passing system

when i press the button the ball goes to other player but it comes back.

and ball is goes to other player very fast

using System.Linq;
using UnityEngine;

public class Passing : MonoBehaviour
{
    private Passing[] allOtherPlayers;
    private Ball ball;
    private float passForce = .7f;

    private void Awake()
    {
        allOtherPlayers = FindObjectsOfType<Passing>().Where(t => t != this).ToArray();
        ball = FindObjectOfType<Ball>();
    }

    private void Update()
    {
        if (GetComponent<Player>().isHaveBall)
        {
            float horizontal = Input.GetAxis("Horizontal");
            float vertical = Input.GetAxis("Vertical");

            Vector3 direction = new Vector3(horizontal, 0f, vertical);
            Debug.DrawRay(transform.position, direction * 10f, Color.red);

            var targetPlayer = FindPlayerInDirection(direction);

            if (targetPlayer != null)
            {
                if (Input.GetButton("Fire1"))
                {
                    if(targetPlayer.tag == this.gameObject.tag)
                    {
                        GetComponent<Player>().isHaveBall = false;
                        GetComponent<Player>().isControlling = false;

                        targetPlayer.GetComponent<Player>().isHaveBall = true;
                        targetPlayer.GetComponent<Player>().isControlling = true;

                        PassBallToPlayer(targetPlayer);
                        Debug.Log(targetPlayer.name);
                    }
                }
            }
        }
    }

    private void PassBallToPlayer(Passing targetPlayer)
    {
        var direction = DirectionTo(targetPlayer);

        if (direction != null)
        {
            Vector3 ballToPlayer = new Vector3(direction.x * passForce, 1.0f, direction.z * passForce);
            ball.gameObject.GetComponent<Rigidbody>().velocity = ballToPlayer;
        }
    }

    private Vector3 DirectionTo(Passing player)
    {
        return Vector3.Normalize(player.transform.position - ball.transform.position);
    }

    private Passing FindPlayerInDirection(Vector3 direction)
    {
        var closestAngle = allOtherPlayers
            .OrderBy(t => Vector3.Angle(direction, DirectionTo(t)))
            .FirstOrDefault();

        return closestAngle;

        // Non-LINQ Version
        //Passing selectedPlayer = null;
        //float angle = Mathf.Infinity;
        //foreach(var player in allOtherPlayers)
        //{
        //    var directionToPlayer = DirectionTo(player);
        //    Debug.DrawRay(transform.position, directionToPlayer, Color.blue);
        //    var playerAngle = Vector3.Angle(direction, directionToPlayer);
        //    if (playerAngle < angle)
        //    {
        //        selectedPlayer = player;
        //        angle = playerAngle;
        //    }
        //}
        //return selectedPlayer;
    }
}```
#

idk where is the problem

#

and the other script

woeful leaf
#

You should not run a GetComponent<> in the Update like that

cedar pivot
#

thanks

woeful leaf
#

You should cache the player

#
private Player player;
private void Awake()
{
  player = GetComponenet<Player>();
}
#

And this as well

thin aurora
# cedar pivot hi i have a problem at my passing system when i press the button the ball goes ...

Can't help you with the problem. I can help you with your coding style, though.

  1. Like Wumpie said, don't have GetComponent<Player>() in your code. Store it in memory when you call Awake.
  2. Add guard clauses to your code, to avoid nesting. Instead of checking if (GetComponent<Player>().isHaveBall), check if (!GetComponent<Player>().isHaveBall) and add a return; keyword. This makes your code much more readable.
  3. FindObjectOfType and FindObjectsOfType are bad for performance and generally a bad idea to use, as they can easily cause problems. Consider getting your components another way
tough osprey
#

Can I have a variable in a ScriptableObject be another script (not to a prefab) that is of a specific type? I have configuration ScriptableObject that defines how to create variations of a type and I want to define a script that should be added to the GameObject that I'll create at runtime.

cedar pivot
#

thanks @thin aurora & @woeful leaf

#

im updating my script

tough osprey
late lion
# tough osprey eg, I could put a script name in the config ScriptableObject and then do somethi...

There isn't a built-in way to do this, but it's trivial to make a custom serializable type that saves the name of the type as a string, but exposes it as a dropdown in the editor. For example:
https://github.com/SolidAlloy/ClassTypeReference-for-Unity

GitHub

Property drawer that allows class selection from drop-down in Unity. - GitHub - SolidAlloy/ClassTypeReference-for-Unity: Property drawer that allows class selection from drop-down in Unity.

normal stump
#

is there a unity library nuget package? I want to import in a netstandard2.0 class library to share certain types like vectors

thin aurora
normal stump
thin aurora
normal stump
#

why not?

thin aurora
#

I made a multiplayer package and I also tried to do it outside of Unity, but Unity has too many limitations to do this

#

One simple thing I can think of right now is how Unity can't work with constructors, and how you can't use monobehaviours in general

normal stump
#

I don't want mono behaviours

cedar pivot
thin aurora
#

You might aswell make a blank .NET Standard 2.0/2.1 project without Unity

normal stump
#

I just want model classes so that the API can communicate

tough osprey
normal stump
#

but I want certain types in those models

thin aurora
#

There's no package that does this

normal stump
#

yeah

#

thanks will try

thin aurora
#

I believe, since Unity compiled in .NET Standard 2.0, you can also extract your build DLLs from a build and reference those

#

If you make an asmdef folder specific for API stuff you would get it as a dll

normal stump
#

it's what I'm doing rn

late lion
thin aurora
#

Probably still requires UnityEngine though

normal stump
#

no harm there

cedar pivot
#

the problem is

normal stump
#

can't import them all

whole yew
#

when clicking on a UI input field, it automatically highlights all the text that was typed in and if you start typing, it will delete everything, is there a way to make sure the text isn't selected so that the user can just continue typing without all the text being deleted?

thin aurora
#

Usually Nuget or Unity's package manager handles this

#

Have fun ๐Ÿ™‚

polar marten
#

what is your goal?

polar marten
normal stump
polar marten
#

you can create a project using dotnet project with netstandard21 as the framework, add your package, then publish it. all the dependencies will be gathered for you. you will have conflicts with unity supplied dlls that you can resolve with ignore version verification. good luck

normal stump
#

yeah I figured I won't do it

polar marten
#

this is not practical

#

you can use the unityengine stub dlls people publish

normal stump
#

I will just make my own Vector3, since it's the only model I wanted

polar marten
#

you can also reference it directly on your system, which will work

tough osprey
# polar marten what is your goal?

So I have many layers. Terrain layers like water, desert, grass, etc. Object layers like trees, mountains, etc. Other layers like ChopTreesHere, MineHere, PowerLines, etc (not named those). I also support mods providing definitions and handlers for whatever layers they want to add, eg a Gas Pipe Layer.

Since my game is entirely procedurally generated, I'm not hand crafting anything in the editor. I'm also trying to avoid preconstructing these layers because I don't expect modders to preconstruct anything.

Currently I load all Configurations from Resources, cycle through each Config and build the layer as defined, which includes attaching the referenced handler to that layer.

Does that make sense?

polar marten
#

of your game

normal stump
#

can I use a Task to update gameobjects asynchronously?

tough osprey
# polar marten do you have a screenshot handy?

lol, super early prototype but here. Currently working on Zoning layers which is where the layers start to actually become managed. I can draw previews but working on creating a ChopTrees zone that will be managed.

polar marten
polar marten
#

are you sure there is any value in that?

normal stump
#

to run code on the main thread

polar marten
solid mountain
#

hey some help

polar marten
tough osprey
normal stump
#
async Task()
{
  while (true)
  {
    await InvokeMainThread(()=>{ });
  }
}

@polar marten

solid mountain
#

i'm making a rythm game and sometimes unity lags a little when loading and then the moving stuff are late and the music is sounding off

polar marten
#

then if people want to make changes they can pull request it to you in github. if they cannot practically use the github UI, they will not be making interesting mods to a simulator anyway

polar marten
#

take a look at unitask

normal stump
#

it's a package?

polar marten
#

yes

normal stump
#

aight

#

will have a look

tough osprey
polar marten
#

anyway, it's your call

tough osprey
#

Also, this plugin model feels right to me, but I'm guessing it's a anti-pattern in Unity

polar marten
#

you are at the start of a long journey

polar marten
tough osprey
tough osprey
polar marten
#

it is a long journey to

and make some money from it
i am trying to say rimworld guy had already worked on many successful games, at a studio that actually later imploded, so serendipity had a big role

tough osprey
#

Yeah, and as someone with a fulltime job and a family, I temper my expectations already ๐Ÿ˜›

#

Still fun to work on and imagine an eventual end. For the moment, just a fun side project POC

normal stump
#

is is bad for performance to get the transform of game objects without caching?

#

like, do I save a transform field or gameobject field?

leaden ice
#

if not both

normal stump
#

alight

leaden ice
#

It's actually rare that GameObject is the best type for a reference

#

usually you're more interested in some particular component on the GameObject

normal stump
#

I see

tough osprey
# lucid valley are you using that for mods?

Partly, and also it simplifies my process. I find it easier to create a new resource folder, drop in some textures, define a config, and let my existing code integrate it without needing to create a Tilemap in the editor and configure everything.

leaden ice
#

GameObject is only useful if you want to do something involving the active state of the object or its layer

polar marten
#

personally i would try to implement as much of the game as possible myself, without any notion of plugins, and once it actually works, pluginify it

lucid valley
polar marten
#

you will not have the wisdom for how to do plugins before a working game exists

tough osprey
polar marten
#

that is my polite way of saying that the architecture for plugins is bad

tough osprey
polar marten
#

it's really hard to say

tough osprey
#

I don't mind brutal honesty

polar marten
#

lol

#

on the other hand, i think i have a hard time seeing a bigger picture here because i don't play rimworld

#

i played a lot of cities skylines, but then i stopped playing

#

i never tried modding it

#

i author an open source game, and it has an audience, and people make the pull requests the way i describe, but end users are authoring text assets

eternal tusk
#

How do i change the y axis of the gameobject without affect the x or z axis

polar marten
#

and i had an a-priori thesis for a moddable (community authored) game that would have an audience, that wouldn't really fit for a city builder

#

other than the game i made, it would make more sense for (1) a game about shoes, (2) a game about hotwheels/cars

leaden ice
polar marten
eternal tusk
#

my gameobject would be rotate around an cube, but i want to change the y axis only

lucid owl
#

could someone help me with a unity project i downloaded?

eternal tusk
#

Red: Rotate around
Blue: Moving y axis.
I want to control what height (Y axis) would the gameobject be rotating.

lucid owl
polar marten
#

@tough osprey so basically what i am saying is
unless you have a very strong thesis for why this game would have a modding community... it's best to focus on a simpler architecture that lets you make a really good game. the thesis "popular games attract mods" is much simpler than, e.g., mine, "a bunch of specific stuff about card games that makes a community authored CCG popular as a consequence of it being moddable"

lucid owl
#

anyone have any ideas what might be the issue?

polar marten
lucid owl
#

I was hoping to do what they said in the video and add custom voice lines and parameters

polar marten
lucid owl
#

though, i look at the comments and more and more people are noting how it doesnt work

lucid owl
#

...i assume that might be a factor

polar marten
#

okay

#

you might want to ask code beginner

lucid owl
#

well, i assumed it was more of a general issue

polar marten
#

you are on the start of a long and fun journey

#

it sounds like you are at the very, very beginning of this journey

zinc parrot
#

when a task is created in unity, is it always on a seperate thread or is there a chance it will be put on the main thread?

leaden ice
zinc parrot
#

oh? I just do this

leaden ice
zinc parrot
#

ah ok cool

#

thanks!

viscid hull
#

sorry for the question but how i do for set somethings on dontdestroyonlaod because my game manager is in the level not in the main menu

#

and i want to set somethings on main menu

vague slate
#

Is there a built in attribute that makes callback on Application quit?
I need some proper cleanup callback for statics

somber nacelle
vague slate
#

interesting

#

thanks

vague slate
#

no mono for me

#

Allthough I have been using mono bridge

#

(hidden go)

#

kinda what I wanted to get rid of in the first place

#

๐Ÿ˜…

#

๐Ÿค”

#

it doesn't work in Editor

#

it seems

scenic creek
#

I'm having trouble with my player movement script. I've been using rigidbody.MovePosition, but I wanted to have collisions work so I switched to rigidbody.AddForce. However this causes my rotation to bug out. I'm using rigidbody.MoveRotation which worked perfectly fine until I switched to AddForce. Now the player will sometimes jitter in rotation.

leaden ice
scenic creek
#

one sec

#
sd.velocity = Vector3.ClampMagnitude(sd.velocity + acceleration, c.maxVelocity * movementMultiplier);
rigidbody.MovePosition(sd.velocity * Time.fixedDeltaTime + transform.position);

Vector3 upDirection = sd.CalculateAverageUp(sd.attachmentDistance);
Debug.DrawLine(transform.position, transform.position + upDirection, Color.magenta);
Vector3 forward = Vector3.ProjectOnPlane(sd.camera.forward, upDirection);
Quaternion targetRotation = Quaternion.LookRotation(forward, upDirection);

rigidbody.MoveRotation(
        targetRotation
    );
leaden ice
#

where is this running

#

Update? FixedUpdate?

#

what is sd?

scenic creek
#

It's a method called by fixed update.

polar marten
#

i believe it supports this style of movement that you are going for

leaden ice
#

plus I thought you said you switched to AddForce

scenic creek
#

ah yes, I accidentally left that part off.

rigidbody.AddForce(acceleration);
leaden ice
#

where?

#

Why not just share your whole script

scenic creek
#

this would be instead of the first two lines of the previous.

leaden ice
#

If you're doing BOTH AddForce AND MovePosition that'll be somewhat problematic.

scenic creek
#

No, I'm not doing both. I comment out the one I'm not using.

#

If it's more clear I can do a pastebin

#

what is the difference between transform.position and rigidbody.position, when the rigidbody is on the same object?

potent sleet
#

no reason not to use the premade kinematic controller

#

why reinvent the wheel

leaden ice
#

they can be different especially in between physics updates, as the Transform may be interpolated for visual smoothness

scenic creek
#

Actually that's relevant to the previous way I was doing it so nvm

polar marten
#

like tracks that will make it harder to achieve what you want

scenic creek
#

ok, so advice?

polar marten
# scenic creek ok, so advice?

so when you do something like this

    [HideInInspector] public ClingState clingState;
    [HideInInspector] public FallState fallState;
    [HideInInspector] public JumpState jumpState;

this is telling you you are making something that is tightly coupled

#

like you can pretend to decouple something by making a class hierarchy and a state machine or whatever

#
    public InputActionReference move;
    public InputActionReference sprint;
    public InputActionReference jump;

but stuff like this is telling you, well it's strongly coupled

#

you can't make a strongly coupled thing like movement, particularly idiosyncratic spider wall clinging movement, and turn it into something decoupled

#

you can pretend it is decoupled

#

but you can't make it decoupled

#

am i making sense?

scenic creek
#

Yeah.

polar marten
#

it helps you organize stuff intellectually and emotionally to have these separate scripts

#

i'm not saying it's bad

#

but it does get in the way

scenic creek
#

Yeah my purpose was mostly organizational.

polar marten
#

but I wanted to have collisions work
going to your original question, you mean collisions in the sense of confining the character movement naturalistically. like the spider cannot move through walls.

#

right?

#

or do you mean the spider should interact physically with something like a swinging pendulum - it would get knocked back by a conventional unity physics object

scenic creek
#

so what I have right now will keep the player from going through walls only to a point. Once it is going fast enough, like when I press sprint, then it will clip right through.

#

So yeah, the first one about going through walls.

polar marten
#

okay

#

can i step back one more time?

#

i think it is valuable to try to author this yourself for education purposes and to make innovative movement

#

and we'll talk about the techniques to scale up to support innovative movement

#

it's about understanding how this works

#

it's worth looking at this asset

gaunt cobalt
#

Hello all, Does anyone know how to select an AR object using Unity AR foundation and then an AR text panel appears? the panel also needs to dissapear after i click on the AR object again. I tried looking for tutorials online but there isn't really anything on this. I only started coding so im slightly struggling on this

polar marten
#

would specific tutorials be helpful? what is an example of something you want to make

gaunt cobalt
#

i want to create a info button object, when selected using raycast, an text panel appears with instructions

west lotus
#

An Ar object is like a regular object. You would raycast from the screen position of the tap into the scene, detect a hit and do what ever you like after that. So you should start with how a tutorial on how to fire a raycast from touch input and detect a object

gaunt cobalt
#

then when im done reading, i can make it dissapear by selecting the info button again

scenic creek
#

I'll look into using the kinematic controller. I didn't think anything that was prebuilt would work for what I'm doing since it's pretty different movement from a lot of games, but I'll see.

As for the moment, is there any way to fix my jittering issue with a quick fix?

polar marten
#

@scenic creek so based on the KCC source, you will be reimplementing, using raycasts, a character controller

distant glen
#

Why is OnMouseEnter() or OnMouseExit() not being called?

scenic creek
leaden ice
#

Also are you using the new input system or the old one

distant glen
distant glen
leaden ice
#

what kind of object is this

#

is it in the game world, or is it UI?

distant glen
teal delta
#

hey there, how can i make bool true after one press of a button and after another set it to false (like a switch)

somber nacelle
#

myBool = !myBool

teal delta
#

thanks

polar marten
scenic creek
#

I think the only part that should be relevant is the part I posted. That entirely controls the movement and rotation in those lines.

distant glen
#

Does anyone know what these build errors pertain to?

#

They've suddenly began.

simple pike
#

How would I get a position of a collision ?
I have a bomb that can be dropped and I'm trying to create an explosion at the impact point
how would I achieve this ?

somber nacelle
distant glen
normal stump
#

how can I get the angle required to face another Vector3 from a Vector3

leaden ice
hard sparrow
#

If you have a conditional shader that you want to be able to turn on and off, do you fold that into your normal shader and have a bool for it, or do you make a second shader and add it as another material on top of the normal one when you need it?

#

Er, no, apparently you can't use bools to control shaders. You have to swap between materials or add new materials

misty jewel
misty jewel
#

I realized if I raycast corners and convert to a box it would require also scaling the box to be bigger/smaller when it's further/closer to the camera which adds a lot more complexity that I dont know how to calculate accurately

main shuttle
# misty jewel just to be on the same page I think this involves converting 2D rectangle to a 3...

It depends on your game. If you have an orthographic RTS camera like AOE2 then you wont need to. If you have a perspective camera, there are instances you need to do what you say. If you would just look down on the map perpendicular, you could also skip that. If you have a perspective camera at an angle, it might be more useful to draw an invisible cube that represents your selection box, that has the vertices changed so that the box starts small and gets bigger at the end.

misty jewel
main shuttle
#

Yeah exactly.

misty jewel
#

thanks I was looking for videos but didnt find what I needed

main shuttle
#

Well if this is what you wanted, then BoxCast isn't the way to go. This isn't a box anymore ๐Ÿ˜›

misty jewel
#

yea it's warped...

main shuttle
#

More like a pyramid.

misty jewel
#

probably

#

that gave me an idea
but video first

#

initial idea is to have a pyramid box collider atwhatcost but will see the video first

main shuttle
#

Well the pyramid is warped too, that's the fun thing about perspective

misty jewel
#

yea...

long fox
#

Any advice to start learning coding for vr

leaden ice
#

then throw in VR stuff when you're comfortable with the basics

long fox
#

Alr done

leaden ice
#

then take a few VR tutorials to learn the basics of VR

misty jewel
#

i went back 5 times to make sure i'm not insane, it was confusing

main shuttle
#

Well the idea is good, not saying the execution was fully correct ๐Ÿ˜›

#

But I have seen this style in other videos too

misty jewel
#

also he casually made this array int[] triangles = { 0, 1, 2, 2, 1, 3, 4, 6, 0, 0, 6, 2, 6, 7, 2, 2, 7, 3, 7, 5, 3, 3, 5, 1, 5, 0, 1, 1, 4, 0, 4, 5, 6, 6, 5, 7 };
without saying why it is like that

main shuttle
#

That's just the first one that came to mind. Also, there are a bunch of examples on stackoverflow

#

Well he sort of explained that part with the box before he wrote that

misty jewel
#

yes sorta

main shuttle
#

0, 1, 2 = a triangle, 2, 1, 3 also, 4, 6, 0 too etc

misty jewel
#

now i get the pattern in the array

main shuttle
#

Is there still a part you don't get?

misty jewel
#

he added vector2 + vector3 * float
which is fine for him but an ambiguous operator for me

pine horizon
#

does something the supports the .net standard 2.0 imply that is also is compatible with the .net framework or no?

polar marten
misty jewel
main shuttle
polar marten
misty jewel
polar marten
#

this is authored by someone on this very discord

polar marten
#

i know you said pyramid, but the reason this maybe has been a struggle is because the shape you are looking for is a frustum

rustic rain
#

would abstraction be helpful in unity

jovial parcel
#

anyone know how to use ImmutableDictionary/List/Array in unity? when i try to use it, i get "unable to access internal class" even though i have using System.Collections.Immutable; at the top

polar marten
polar marten
#

they are strictly not compatible, but usually they are

jovial parcel
ancient sable
#

Does Scroll Rect move based on moving mouse while clicking (dragging), mouse scroll, or both?

misty jewel
misty jewel
willow magnet
#

https://ctrlv.tv/WQqe
Hello,
why is this happening to me? It works for me going forward, but once it has a negative vector, it stalls.

    {
        Vector3 lDirection = this.m_Direction == EscalatorDirection.Forward ? this.transform.forward : -this.transform.forward;

        if (Is.All(collision.collider))
            this.m_Rigidbody.AddForce(lDirection * this.m_Speed * Time.fixedDeltaTime, ForceMode.VelocityChange);
    }```
Thanks for help
zinc parrot
#

Is there a way to tell if a texture in a material has changed from script?

dense arch
#

Why do the Unity docs refer to IL2CPP as a virtual machine?

#

The term seems to be loosely defined but I thought it implied run-time handling of an instruction set like the .NET CIL, if it's done at compile-time then it's just a compiler

#

Or maybe if there is enough run-time abstraction on top of things like memory, it's still considered a virtual machine?

leaden solstice
dense arch
leaden solstice
coarse lion
#

Any ideas on why transform.Translate jitters? This is the first time I've had it behave this way.

-The translation is handled in FixedUpdate, everything else is Update.
transform.Translate(Time.deltaTime * player.walkSpeed * movement);

-walkSpeed is consistent and unchanging
-movement is consistent and unchanging (ex. moving left results in Vector2(-1.00, 0.00))
-Time project settings are unchanged from default (0.02 fixed timestep, max timestep 0.333..., timescale 1)
-Based on one forums answer, I've tested with Auto Sync Transforms both enabled and disabled, there's no difference.

uncut lintel
#

Guys, I found out how to properly obfuscate code so nobody will ever be able to read/steal it.
-Don't use obfuscation tools
-Ctrl+A to select your entire script and "Join Lines" to convert your entire 15,000+ lines of code into 1 line.
-That's it, you win.
(satire)

swift falcon
zinc parrot
#

What can write to the albedo gbuffer? I am displaying just the albedo gbuffer texture
and its not just albedo
its like albedo affected by metallicness

#

using the gltf importer shader

polar marten
#

you have exceeded our knowledge

zinc parrot
#

sorry was being stupid
its combined in the diffuse albedo and specular albedo

polar marten
#

okay

#

it was a very strange question

zinc parrot
#

got it in my head that diffuse albedo was just albedo, not just diffuse albedo

polar marten
#

albedo is albedo. math is math.

zinc parrot
#

yes

#

my thoughts exactly

polar marten
#

lol

hard sparrow
#

Trying to change intensity of hdr color through code. If you do myColor x myColor, is that the same as doubling the intensity?

#

oh, found this actually

fierce portal
#

hey everyone,
this might not be the right place to ask, but does anyone know how i can implement steam's microtransaction api into unity? or at least send me a link to documentation? thanks

hard sparrow
#

microtransactions ๐Ÿ˜’

fierce portal
#

fr

stoic sluice
#

Seeing a warning about unreachable code here, which doesn't make much sense.

#

Ahh, the loop always bails.

#

Never mind that makes perfect sense

round owl
#

hello

olive berry
tidal shadow
#

Overly complicated using unity

orchid bane
#

If you have to do it procedurally it isn't that diffcult actually. Given you have a bit of logic and math knowledge

void basalt
#

So I'm looking to pack up an animation state and send it over a network, so that it can be recreated perfectly. Is there generally a good way of doing this efficiently?

#

So like if multiple animations are being blended together, I need to get that somehow, along with the current animation %

elfin vessel
#

C# question: How do I tell if a Type is a string or an int?

#

I cant do a typeof on those

mellow sigil
#

in what context

leaden solstice
elfin vessel
#

I've got a function, that turns a Type into a string. For most Types it will be just the name, but I have a few special cases for string, float, int, etc

#

it's for an editor tool

#

not a plugin. it's, a utility

leaden solstice
elfin vessel
#

oh. well. i can... do that, yeah. A switch statement was giving me nonsense so I thought i couldnt do it. I may need to go to bed. Thanks

leaden solstice
#

You canโ€™t use typeof for switch case bc typeof does not count as compile time constant. However you can do type pattern matching with actual object

plucky inlet
#

Ha, just tested another case, already ran into an issue ๐Ÿ˜„ Nvm, I delete that

thin aurora
#

Indeed, that's not how it works lol

marsh barn
#

Hi Everyone ๐Ÿ™
I want to create a referral programme in my android app that i'm developing in unity. The android way of referrals uses the Play Install Referrer Library to retrieve the information of the referrer if the app is downloaded using a referral link from playstore. I'm not able to find out how to do this in unity. Found some plugins in asset store but they don't seem to frequently used or maintained. Would highly appreciate some expert advice on how people do this in their Android/iOS apps.

leaden solstice
#

Not a good way. Types in different namespace can have same name.

#

Typeโ€™s name is not a type

plucky inlet
#

This attitude tho ๐Ÿ˜„

leaden solstice
#

How are you gonna use nameof for full name? Lol

plucky inlet
leaden solstice
#

Oh itโ€™s okay my goal is not convincing him

#

My goal is to show that it is a dumb idea so no one else do that

thick gale
#

when you update a game, does it change the save json that is in place? Or is there something you have to add to your json save that makes it stay even when the game gets updated?

plucky inlet
thick gale
#

I have a json save script, It saves on a button, it loads when the app starts, But I was wondering if it will clear the json when i update the app, I save to the path Application.persistentDataPath + "/saveFile.json"

plucky inlet
thick gale
#

alright, sounds like a uninstall will clear data then yes, which I would expect it to

plucky inlet
thick gale
#

I will have to test that, thank you for your time twentacle!

thin aurora
leaden solstice
#

I already have given a better solution. Either use if instead of switch-case or do type pattern matching.

brittle sparrow
#

What is a good way to approach memory-leaks? I pressed one of my buttons, and it just froze Unity, and in task manager it was like inflating with memory.

neat lagoon
#

you have to just think through your code and try to find the infinite loop (which is what I am assuming it is)

#

'while' loops are the first place to check

#

then 'for' loops

brittle sparrow
#

wait infinite loops can cause memory leaks?

thin aurora
knotty tulip
#

I have 4 toggle options which are part of a group so only 1 can be selected at a time. The behavior works correctly but for some reason the checkmark does not appear when it is clicked even tho it is selected. Anybody have an idea why that might happen?

neat lagoon
#

I am assuming when you say it "froze unity" that it didn't unfreeze

thin aurora
#

Unless you wrote unsafe code

#

Then the problem is bigger

brittle sparrow
#

yeah i don't use idisposable

thin aurora
#

A memory leak usually doesn't freeze Unity immediatley

main shuttle
#

Just check your button code. If you click the button and it freezes, the problem is there somewhere.

neat lagoon
#

yeah... but an infinite loop would...

brittle sparrow
#

well yeah but

#

i have so much inbetween button behavior

neat lagoon
#

can you explain your issue more clearly @brittle sparrow ?

knotty tulip
#

it used to work before i changed images but I tested the same images on a new one and it worked

main shuttle
brittle sparrow
#

it's nothing much it's just Reset Data breaking

knotty tulip
neat lagoon
#

yes, but you say Unity freezes and inflates with memory

main shuttle
neat lagoon
#

does it ever unfreeze?

brittle sparrow
#

actually if it happens with Save/Load data then great i have less code there

#

yeah posting screenshots

#

okay cancel! I put a for loop without an i++ jesus

#

thanks everyone i looked more clearly at my code

#

sorry for wasting your time

neat lagoon
#

how would that ever unfreeze then?

brittle sparrow
#

yeah..

neat lagoon
#

what do you mean "yeah" holy cow I have asked whether or not it unfroze or not like 4 times lol

brittle sparrow
#

oh

neat lagoon
#

like did it or did it not unfreeze

plucky inlet
brittle sparrow
#

no it just stayed frozen so I moved down to taskbar

plucky inlet
#

how should it ever reach 2 if you do not set it to i++

brittle sparrow
#

yeah the problem is fixed though

neat lagoon
#

okay yes so the whole discussion about memory leaks was pointless, which is why I was asking

brittle sparrow
#

sorry

normal stump
#

hey

#

so basically I have a turret, it has an arm and a weapon

#

when I give it a Vector3 as target I want it to turn at a certain max speed towards the target

#

how can I get the required angle/rotation in order to face the target?

neat lagoon
#

the direction vector is always (targetPos - currentPos).normalized

#

and you can just plug that directly into Vector3.RotateTowards

vague tundra
#

@normal stump Vector.Angle or Vector.SignedAngle is something that I'd normally use too

normal stump
#

alright thanks

#

radian is X or Y?

vague tundra
#

Regarding the max speed, you could look at using Vector3.Lerp, or Mathf.clamp to set a hard limit on the rot speed

normal stump
#

ok

vestal crest
#

Im currently working on how ram works stack and heap and i wonder something. Value types are allocated in stack and reference types are allocated in heap basicly i know this is not true but let me ask my question. lets say i have a test class which inherits from monobehaviour. I declared a private int x = 5; this "x" is allocated in stack or heap? I mean its value type yes should be stack but its in a class so im kinda struggling here. is it allocated in heap now?

#

im having hard times with heap and stack

main tree
#

Hello, I'm not really good at english so sorry first,
I'm using Photon and I can't give a nickname to player.
This code gives NullReferenceExpection error. I'm sure the object which has this code has Photon View component. What can be reason?
GetComponent<PhotonView>().Owner.NickName = "player1";
User connects to master, lobby and room before this.

vague tundra
#

Class C inherits from class B inherits from class A

I have an object of class B.
I want to check whether the object is also class C.
Can I say:
if(B as C) { //stuff } ?

quartz folio
vestal crest
#

when i declare an private int in a class will it be allocated in heap?

plucky inlet
plucky inlet
vague tundra
plucky inlet
# vague tundra Sorry I don't quite follow

you can say if(this is YourOtherClass) or if this.GetType() == typeof(YourOtherClass). not tested, but something like that ๐Ÿ˜„ intellisense will fix my errors ๐Ÿ˜‰

vague tundra
#

Oh cool that makes sense! Thanks:D

potent glade
#

is there a way to move a game object INSIDE a camera's filed of view (orthographic camera), I want to move my Object to the lower right point of the camera Field of view

plucky inlet
thin aurora
#

frontObject.transform.position = Camera.main.transform.position + Camera.main.transform.forward * distance;

plucky inlet
#

in the field of view, not in front...

fiery warren
#

So I have a towerdefense type game. My issue is that I could place weapons on other weapons cell which should be occupied. Here are my scripts for them.
Mainscript is in Update function.

Main Script: ```cs
if (mapManager.IsWeaponArea(mousePosition) && !mapManager.IsOccupied(mousePosition))
{
//My stuff
}

Second script:
```cs
public bool IsOccupied(Vector2 worldPosition)
    {
        Vector3Int gridPosition = map.WorldToCell(worldPosition);

        //This if statement is broken I think, it blocks the player from placing the weapon everywhere except the cell where mouse was during the click.
        //If I remove Input.GetMouseButtonDown(0) I can't place the weapon anywhere.
        if (!occupiedTiles[gridPosition.x, gridPosition.y] && Input.GetMouseButtonDown(0))
        {
            occupiedTiles[gridPosition.x, gridPosition.y] = true; //Mark the tile as occupied
            return true;
        }
        else
        {
            return false;
        }
    }```
potent glade
#

wait that is a different page

thin aurora
plucky inlet
#

They are placing the object in front of the camera, thats not what you want

potent glade
#

yeah I need to know the point of the lower right point of the camera

#

i am looking into it

plucky inlet
#

Thats what I said. You should check ScreenToWorldPosition and the camera values like clipplanes and/or screen size

thin aurora
#

Camera.main.transform.position and you move the object to the bottom right depending on camera bounds

plucky inlet
#

oh my god ๐Ÿ˜„

potent glade
thin aurora
#

Part of life

potent glade
#

true

empty hollow
#

Hello, I like using if statements as guard clauses, to stop further code execution inside a method if the if statement is true.

However, when trying to do that with an inherited method, it does not seem to work. Regardless of the StartActivity base, code keeps executing in the child class. Can someone point me towards a solution to this ?

vestal crest
#

I still didnt get an answer to my question (i cant figure it out either). when i declare a value type in a class, will it be allocated in heap or stack

main shuttle
# main tree .

GetComponent<PhotonView>().Owner.NickName
GetComponent<PhotonView>() can be null and then Owner can be null.
Check if your gamobject with this script has a PhotonView, and then check if it has an owner. You can also just add 2 debug.logs in front of that line with these 2 parameters.

main tree
#

I will test this, thanks

thin aurora
main tree
thin aurora
#

And try-catch it. The if-statement should not happen with normal behaviour anyway

thin aurora
#

If it's possible to be null, change the line to this:

var photonViewComponentOwner = GetComponent<PhotonView>().Owner;
if (photonViewComponentOwner != null)
{
  photonViewComponentOwner.NickName = "player1";
}
#

If it's not supposed to be null, you should figure out how it can be null

#

You can also change your code to this for a clearer error.

var photonViewComponentOwner = GetComponent<PhotonView>().Owner;
if (photonViewComponentOwner == null)
{
  throw new Exception("owner is null!!");
}
photonViewComponentOwner.NickName = "player1";
main tree
#

Well, it can't be null :(

thin aurora
#

I don't know photon. I assume you're missing some settings

main shuttle
main tree
#

Thank you all ๐Ÿ‘

misty jewel
# polar marten okay. unfortunately doing this in a general way is pretty complicated. you can t...

Hey I'm using this currently and it's working great
Everything so far worked except OnTriggerExit (but OnTriggerEnter works)
||I read that it could be a bug or a weird behavior where events are raised for children on enter and for parents on exit..||
Am I missing something?

void _OnTrigger(Collider other, bool entering) {
   //Common stuff
  if (entering) ...
  else ...
}
void OnTriggerEnter(Collider other) {
  _OnTrigger(other, true);
}
void OnTriggerExit(Collider other) {
  _OnTrigger(other, false);
}
plucky inlet
misty jewel
#

In log it says enter enter enter......
But 0 exit
I didn't include the full code here

plucky inlet
thin aurora
#

Also, where did you read about there being a bug?

misty jewel
#
void _OnTrigger(Collider other, bool entering) {
   //Common stuff
  Debug.Log($"{(entering?"Enter":"Exit")} :: {other.gameObject.name}");
  if (entering) ...
  else ...
}
void OnTriggerEnter(Collider other) {
  _OnTrigger(other, true);
}
void OnTriggerExit(Collider other) {
  _OnTrigger(other, false);
}
plucky inlet
#

oh wait, not mouse but on fixed update?

#

how do you move it tho, transform.position or physics based?

misty jewel
#

The movement of the frustum shape is handled by the package
Imagine a 2D rectangle converted to a pyramid

plucky inlet
normal stump
#

I'll ask the question again then

#

I have this turret

#

I only want the arm to rotate on the up axis to face the weapon towards a target

#

how can I get the required rotation for just the arm

#

I have tried moving the entire thing with quaternions

var direction = (target.position - transform.position).normalized;

// 1st attempt (this moved the entire prefab)
var lookRotation = Quaternion.LookRotation(direction);
var s = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * MaxArmAimSpeed);
misty jewel
plucky inlet
misty jewel
#

The other object is placed with NavMeshAgent (position also I suppose)

misty jewel
#

(accuracy is not vital in my case)

wispy fable
#

How can I invoke a function on the main thread from a background thread and return a value? I'm currently using a concurrent queue to enqueue a command that is dequeued and executed on the main thread, but I'm unable to return a value to the background thread. How can I do this?

plucky inlet
plucky inlet
misty jewel
thin aurora
wispy fable
#

I have a HttpListener working on a background thread listening for commands. These commands need to execute behaviour on the main thread and return a response

#

The way I have it set up is that it invokes a strategy which returns a type which is then serialised and send as a response

#

I'm only implementing the strategy behaviour

thin aurora
plucky inlet
thin aurora
#

Also, my solution should use a ConcurrentQueue, not a List.

#

Giving it back to the calling thread is very complex. Not sure if that's possible. You would need to maintain access to the context, which goes over my head.

wispy fable
#

Something like

  public interface ICommandBehaviour {
    public CommandResponse HandleCommand(ICommand command);
  }

On the background thread a HttpListener is running and waiting for requests.
In pseudo; Wait for request, parse request, get response from ICommand, serialize it and respond.

plucky inlet
wispy fable
#

To access components

#

I can't access them from outside the main thread

plucky inlet
wispy fable
#

precollected?

plucky inlet
#

Before you run background thread, do oyu have your components ready?

wispy fable
#

They are referenced if that's what you mean

plucky inlet
#
 private async void WaitForData()
        {
            while (WebRequester.requesting)
                await Task.Delay(1000);

            await Task.Run(() => {
=> This is in a background thread afaik
                Debug.Log(products.Count);
            }); 
        }
#

So the async void is mainthread, the task.run is background

#

Correct me if I am wrong ๐Ÿ˜„

plucky inlet
#

Just to clarify, afaik, you can not call into a thread itself. You can just call a thread and add events to it so it will run them whenever you want them to be called inside that specific thread

wispy fable
#

It's a server that is running on a background thread, not a client. I've just tried manipulating TextMesh from the background thread and it crashed afaik since no response was received

plucky inlet
wispy fable
#

It's just a simple HttpListener

#

I have a component which starts the listener on a background thread

plucky inlet
#

Okay, then just make your mainthread call your events list and feed it with the background thread?

thin aurora
#

Use async Task and handle the process

#

async void is going to crash your system as soon as anything goes wrong

plucky inlet
wispy fable
plucky inlet
thin aurora
plucky inlet
#

you can also have a callback object that just holds a state. This gets send to mainthread, mainthread updates the state and your backgronud could listen for those objects to change. Thats just theory, might work

wispy fable
#

I currently have

// Background thread
public CommandResponse HandleCommand(ICommand command)
{
  commands.Enqueue(command);
  // Somehow return the result
}

// Main thread
void Update()
{
  if(commands.TryDequeue(out ICommand command))
  {
    switch(command)
    {
      ...
    }
  }
}
plucky inlet
#

I guess you gotta go with some object based approach

wispy fable
#

In WPF you can get the dispatcher for the main thread to invoke on there. Is there no such way to do it in Unity?

plucky inlet
thin aurora
#

Doing this manually is not possible as far as I know

thin aurora
#

Perhaps you can use TaskScheduler.FromCurrentSynchronizationContext() to get the current context, which I have been hinting about for a while now. Since this goes way over my head I can't give you a solution that uses this, but this seems like a start when it comes to switching threads, since it depends on the thread context.

#

Perhaps you can use my previous solution of creating a monobehaviour to store a ConcurrentQueue of Action types, and have them accept a context from this method. Maybe the main thread can then send the response back as an object, after a main thread handles this queue.

misty jewel
#

@plucky inlet I ended up using OnTriggerEnter + short timeout delay
Works great for my usecase (accuracy doesn't matter)

#

So it keeps updating the time while still colliding
And it skips selection if it hasn't collided for x time delay

#

After a small test, looks great even tho it's not accurate

plucky inlet
thin aurora
plucky inlet
#

Background to Main and back threading

vague sedge
#

i need help figuring out if a eulerangles.y angle is between two other angles

for example:
the players eulerangles.y angle is 349

and i need to find out if its between 281 - 101 (which it is) but idk what to write to check this the way i want to

#

            var from = SplineRotationY - 90;
            var to = SplineRotationY + 90;

            if (from < 0) fromFixed = from + 360;
            else fromFixed = from;
            if (to > 360) toFixed = to - 360;
            else toFixed = to;

            if (player.transform.rotation.eulerAngles.y >= fromFixed && player.transform.rotation.eulerAngles.y <= toFixed)
            {
                player.splineDirection = true;
                Debug.Log("forward");
            }
            else 
            { 
                Debug.Log("backwards");
                player.splineDirection = false;

            }```
#

this is what ive wrote but im not a programmer so im pretty sure this is wrong

vague sedge
#

ill try that, i cant get the railSpline.transfrom.forward i can only get its position and rotation

steady moat
#

Quaternion.Angle(Quaternion.AngleAxis(AngleA, Vector3.up), Quaternion.AngleAxis(AngleB, Vector3.up));

#

Also, eulerangle is between -180 and 180 if I remember correctly.

vague sedge
#

nah its 0 - 360

#

but thankyou for the response โค๏ธ

vague sedge
#
angleDiff = (player.transform.rotation.eulerAngles.y - SplineRotationY + 180 + 360) % 360 - 180;
if (angleDiff <= 90 && angleDiff >= -90)
{
  player.splineDirection = true;
  Debug.Log("forward");
}
else
{
  Debug.Log("backwards");
  player.splineDirection = false;

}```

figured it out
steady moat
#

the formula is angleDiff = Quaternion.Angle(Quaternion.AngleAxis(player.transform.rotation.eulerAngles.y, Vector3.up), Quaternion.AngleAxis(SplineRotationY, Vector3.up));

#

The number will be between 0 and 180

swift falcon
#

Is it possible to loop through each SerializeFields in a Header?

#

Or rather loop through the Header looking for each SerializeFields

thin aurora
swift falcon
#

Well the one in inspector

thin aurora
#

typeof(myType).GetProperties(accessorFlags) gives you PropertyInfo[]. Each PropertyInfo has a getCustomAttribute<TAttribute>() method to get the HeaderAttribute. If it's not null, you reached a header. If you want a specific header, you should check the attribute that way.

#

accessorFlags in this case is the flags to search on. I forgot what they are called. But you should check for instance, and private/public depending on what your properties are

#

If your serializefields are actually on fields, you should do typeof(myType).GetFields(accessorFlags) instead

tired fiber
#

Guys i need help with code, someone help?

thin aurora
#

@swift falcon what is the exact thing you want from this? I can try and create something

#

Since it's probably confusing

tired fiber
#

?

thin aurora
swift falcon
tired fiber
#

there was nothing special?

thin aurora
thin aurora
#

You should probably create a script that disables them all manually...

#

But, since I'm bored, I can make an enumerator for you.

swift falcon
woeful leaf
shy heath
#

I'm trying to have a component be able to save while in play mode

woeful leaf
#

Define save

thin aurora
#

And ChatGPT aint helping

woeful leaf
woeful leaf
shy heath
#

cinemachine has an implementation for it

#

that it says can be used for other components

woeful leaf
#

Use Scriptable Objects

#

If you change a value of a Scriptable Object, it'll be saved after you close the scene

#

Though this is only in editor mode

#

Don't try to use it as a save system

shy heath
#

so i want to know if im missing any intermediary steps

woeful leaf
#

I mean it's only for tweaking and later it won't be used anymore right?

#

Also show the code to see if you applied it properly

shy heath
#

it might be used as an internal tool

woeful leaf
#

SO can also be used as an internal tool

woeful leaf
#

And always google1google2google3 ,maybe there are some solutions online

shy heath
#

there are other solutions for which i might have to adapt their code (which is fine ig, but this will save me a ton of time)

woeful leaf
# shy heath

I don't know if this is a "Cinemachine Component" since it just derives from MonoBehaviour, but I don't know much about Cinemachine

shy heath
woeful leaf
shy heath
#

alright

#

thanks so much !

thin aurora
#

Apparently they're bindingflags

#

But I would strongly recommend just doing it manually

#

Reflection for this is unecessary

swift falcon
#

Is there another way to do this?

thin aurora
#

I was writing code for this but it's just a lot to account for every problem that could happen with reflection

thin aurora
thin aurora
#

But you should do it manually, and not reflection

thin aurora
#

Just the completed level?

swift falcon
#

From the main menu

thin aurora
#

What happends if they're on?

swift falcon
#

If you click on it it calls my LoadLevel function

thin aurora
plucky inlet
# swift falcon No they're levels

Codewise, they are not levels, they are UI elements that load a level, right? So you can just store them in a list or create buttons depending on the last levels you played. all up to you

thin aurora
#

What about having a List<Button> in your class, and store a reference there?

#

Then you can iterate until the button that should be on

#

And you can check that by just comparing current index +1 against the level

#
[SerializeField] private List<Button> _levelButtons;
private void setLevelButtons(int level)
{
  // Disable all
  foreach(var levelButton in this._levelButtons)
  {
    levelButton.enabled = false; // Or whatever the way to disable it is.
  }

  // Enable
  foreach(var levelButton in this._levelButtons.Take(level))
  {
    levelButton.enabled= true; // Or whatever the way to disable it is.
  }
}
#

Something like this

#

Then you can also skip levels, and go back

#

You can't skip levels and keep them disabled, though. That's more work.

swift falcon
thin aurora
#

Take in this case only returns up until that level, basically

#

That's why the loops are basically identical

swift falcon
#

I didn't know SerializeField could make a list, thanks

thin aurora
#

I believe List works. Otherwise it needs to be an array

#

Arrays works too with this code

swift falcon
#

๐Ÿ’ฏ

woeful leaf
thin aurora
#

Happy days

floral needle
#

Hey guys, I want to be able to construct my damage class via ScriptableObject OR by giving it the specific parameters. Is there a better way to do this or is my approach the best I'm gonna get?


public class Damage : MonoBehaviour
{
    float _amount;
    float _addForce;
    int _tickAmount;
    float _damageOverTimeDuration;
    DamageElement _element;

    public Damage(DamageInfo damageInfo = null, float amount = 0, float addForce = 0, float tickNum = 1 /*...*/)
    {
        // if damageInfo is null Construct with Parameter values ... else :
        _amount = damageInfo.amount;
        _addForce = damageInfo.addForce;
        _tickAmount = damageInfo.tickAmount;
        _damageOverTimeDuration = damageInfo.damageOTDuration;
        _element = damageInfo.element;
    }


woeful leaf
#

!cs

tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
plucky inlet
floral needle
#

thx xD

swift falcon
woeful leaf
#

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

woeful leaf
#

Pastebin

thin aurora
#

@swift falcon

swift falcon
#

๐Ÿ™

thin aurora
#

Since an array and a List both implement IEnumerable, this method is valid on them

woeful leaf
thin aurora
#

Linq is the greatest shit you will ever learn about

#

Well maybe not

#

But it will help

#

A lot

floral needle
woeful leaf
#

Well you can overload constructors

plucky inlet
oblique spear
floral needle
#

Thanks for the help!

plucky inlet
woeful leaf
#

Picks the one based on parameters @floral needle

#

It's the same as method overloading but then for constructors

oblique spear
plucky inlet
#

so setfloat on the animator all the time, without if statements

woeful leaf
thin aurora
woeful leaf
#

Also that

thin aurora
#

i.e.

public class Damage : Monobehaviour
{
  public void Initialize()
  {
  }

  public void Initialize(int val)
  {
  }

  public void Initialize(int val, string val)
  {
  }
}
swift falcon
#

what is Initialize method? Did I skip a part in unity beginner?

woeful leaf
#

No it's just a method he made lol

thin aurora
#

It's a method you make yourself.

oblique spear
floral needle
#

Derp moment

swift falcon
#

just something you Initialize() in awake?

woeful leaf
swift falcon
#

oki oki

plucky inlet
plucky inlet
swift falcon
#

I dont get it blushie

plucky inlet
#

If you use monobehaviour, you have to use it as a component. If you just use it as a class, you can create it just for data source that then can be used in your components on the gameobjects.

swift falcon
#

The more I dont get it ๐Ÿฅน

thin aurora
#

This is a good way to set data. But this is more for oak.

plucky inlet
#

Just think about how you gonna set up your damage on your items. can you explain that? Do you have like a gameobject of a weapon and than add damage component to it, which is what you get with your monobehaviour?

#

But if you have like a scriptable object item, you could reference a field to the scriptable object damage for example, and from there you just drag drop and create your stuff simpler. But you gotta explain a bit what you want to do with damage

woeful leaf
#

(Each of those items that you can grab has that script)

woeful leaf
#

Yes

plucky inlet
#

is the canvas overlay or camera screenspace?

woeful leaf
#

Screen space

#

nop ovelay

#

Well it's both

plucky inlet
#

Okay, the problem is, the position of your mouse might not be exactly as where your UI is. Did you try to use WorldToScreen with your mouseposition?

woeful leaf
plucky inlet
#

but transform.position is not what you do on UI

#

you position it with rectTranform.anchoredPosition

woeful leaf
#

Oh

#

Lemme see

#

What's so bad about transform.position then for UI elements

#

Also I suppose I've to do a GetComponent for it then since I don't inheritely have it

plucky inlet
woeful leaf
#

hmmm

plucky inlet
#

That is why there are WorldToScreen calculations or ScreenpointToWorld and what not

woeful leaf
#

Righty

woeful leaf
#

Now the position doesn't match the cursor with rect.anchoredPosition = Input.mousePosition;

plucky inlet
#

Cause I guess you gotta set the z value to something to fit it

quartz folio
woeful leaf
plucky inlet
#

to cast your transform to RectTransform

swift falcon
#

Are Get Set methods common practice in game dev/C#? I haven't seen them often in tutorials

woeful leaf
#

I'd think just (RectTransform) in front of it but that doesn't really work

quartz folio
woeful leaf
swift falcon
plucky inlet
quartz folio
# woeful leaf

You need more brackets.
Or you just make a variable on another line

plucky inlet
#

otherwise you would try to cast the position as recttransform

woeful leaf
#

Ah right

quartz folio
somber nacelle
swift falcon
#

Ah could very well be why thanks

woeful leaf
#

((RectTransform)transform).position = Input.mousePosition;

swift falcon
woeful leaf
tired fiber
#

https://gdl.space/dikisemuje.cs, can someone tell me how to fix error: NullReferenceException: Object reference not set to an instance of an object
CraftingSystem.RefreshNeededItems () (at Assets/Scripts/CraftingSystem.cs:186)
CraftingSystem.Update () (at Assets/Scripts/CraftingSystem.cs:116)

plucky inlet
woeful leaf
main shuttle
woeful leaf
#

Which does break the position again

tired fiber
#

So what i need to do?

woeful leaf
#

With that the cursor and the object aren't aligned anymore

tired fiber
#

Im beginner so idk

tired fiber
#

craftAxeBTN.gameObject.SetActive(false);

#

186

#

RefreshNeededItems();

#

116

thin aurora
somber nacelle
# tired fiber Im beginner so idk

#๐Ÿ’ปโ”ƒcode-beginner next time.
but you are using toolsScreenUI.transform.Find("Axe").transform.Find("Button").GetComponent<Button>(); to get the reference, it seems like that is probably not returning what you expect. make sure you also scroll to the first error in your console because this line is likely throwing an error

thin aurora
#

But the code is full of these find methods so who knows what it gets

#

You should get craftAxeBTN in another way

main shuttle
#

But if it wasn't found:

        craftAxeBTN = toolsScreenUI.transform.Find("Axe").transform.Find("Button").GetComponent<Button>();
        craftAxeBTN.onClick.AddListener(delegate {CraftAnyItem(AxeBLP); }); 

I would expect the next line to give an error.

tired fiber
#

So what i need to do?

somber nacelle
woeful leaf
# woeful leaf

Debug.Log($"The position of the object is: {((RectTransform)transform).anchoredPosition}, and the position of the cursor is: {Input.mousePosition}");

main shuttle
#

Oh fair, he could have way more errors then this.

somber nacelle
plucky inlet
graceful patio
#

i have a couroutine question?

#

how can u tell a couroutine finished

#

in C#?

plucky inlet
#

or use async Task that returns a completed event.

tired fiber
#

I get three errors:

woeful leaf
#

When you hold the object it yeets it way off to the right and top

tired fiber
#
  1. NullReferenceException: Object reference not set to an instance of an object
    CraftingSystem.Start () (at Assets/Scripts/CraftingSystem.cs:58)
  2. You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
    UnityEngine.MonoBehaviour:.ctor ()
    Blueprint:.ctor (string,int,string,int,string,int) (at Assets/Scripts/Blueprint.cs:18)
    CraftingSystem:.ctor () (at Assets/Scripts/CraftingSystem.cs:26) and 3. NullReferenceException: Object reference not set to an instance of an object
    CraftingSystem.RefreshNeededItems () (at Assets/Scripts/CraftingSystem.cs:186)
    CraftingSystem.Update () (at Assets/Scripts/CraftingSystem.cs:116)
main shuttle
#

Yeah, so that's what I expected ๐Ÿ˜›

tired fiber
#

So can u help me out?

somber nacelle
#

you need to get a reference in a better way than chaining all of these Find calls

plucky inlet
thin aurora
# graceful patio how can u tell a couroutine finished

A coroutine has no build in way for this. Coroutines are of type IEnumerator, and these only have behaviour on how to keep going. It has a MoveNext method but this is not for checking if it's finished. You should create a seperate boolean outside the code that turns true once the coroutine is finished.

distant glen
#

I have about six different managers in my game.

Only two of these are singletons. This is because my learning resources have led me to the conclusion that the singleton pattern should be used sparesly.

The two classes in my project that implement the singleton pattern are the GameManager and the AudioManager.

The other managers in my game, such as the UIManager, InputManager, and CameraManager, are all passed into my GameManager.

If a piece of code wants to reference certain functions of the UIManager or InputManager, for example, it will do so through certain functions I have in my GameManager, which then references the other managers.

Is this bad design? Should I refactor this, or can I keep using it in this way?

plucky inlet
somber nacelle
plucky inlet
# woeful leaf

Ahhhh, I know the issue, i guess at least. ๐Ÿ˜„ can you show your prefabs inspector of the recttransform component?

woeful leaf
plucky inlet
#

yes

graceful patio
woeful leaf
thin aurora
#

Because this is what a Coroutine is basically

woeful leaf
plucky inlet
# woeful leaf

Just for testing. can you take the prefab you instantiate as text, pick that one and set the anchor to this:

woeful leaf
#

It's not a prefab though heh

#

But I can do it in the code

plucky inlet
woeful leaf
#

Or wait I still need pivot to be 0 as well

#

That did change the position of it

#

But it's not in the center

#

Like it used to be with the old way

plucky inlet
#

You mean in the center of the screen? or what center?

woeful leaf
#

Oh the hitboxes are whack now

plucky inlet
#

Oh you mean the center of the UI object?

woeful leaf
#

Instead of the center of the object

plucky inlet
#

can you try all anchors and pivot to 0.5?

#

Ah wait, anchors to 0 and pivot to 0.5

#

that should be correct

woeful leaf
#

That fixes it :D

#

I still have the first issue though

plucky inlet
#

what was the issue again? ๐Ÿ˜„

#

I thought it was the wrong position ๐Ÿ˜„

woeful leaf
thin aurora
thin aurora
woeful leaf
woeful leaf
thin aurora
woeful leaf
plucky inlet
#

too many topics going on ๐Ÿ˜„

#

Found the link ๐Ÿ˜‰

woeful leaf
#

:D

plucky inlet
#

are you sure you reset your onMouseOver correctly? Did you check those values?

woeful leaf
#

It's kinda hard to check in that case

#

Because it's not like consistent

#

I might have to do with this part

    public void OnPointerExit(PointerEventData eventData)
    {
        if (Input.GetMouseButton(0)) return;

        onMouseOver = false;
        oneIsHeld = false;
    }
plucky inlet
woeful leaf
#

Or some kind of mismatch

plucky inlet
#

UI is behind sometimes, so your code might execute again before the UI position is updated

#

hence the execution order of Update, OnEnable and UI update

woeful leaf
#

Right

#

How would I best check if that is the case?

plucky inlet
#

Is it intended they flip to your position on pointer enter, not mouse down?

#

flip => move ๐Ÿ˜„

woeful leaf
woeful leaf
#

That function doesn't work for my use case though

polar marten
#

@woeful leaf what is the behavior you are trying to achieve?

#

do you want to be able to drag-to-move UGUI elements?

woeful leaf
#

Yeah

polar marten
#

okay

woeful leaf
#

If you click and hold on it it'll follow your mouse position

plucky inlet
#

you could use ```cs
if (EventSystem.current.IsPointerOverGameObject())
{
Debug.Log("Its over UI elements");
}
else
{
Debug.Log("Its NOT over UI elements");
}

To check for being over UI
polar marten
#
class DragToMove : MonoBehaviour, IBeginDragHandler, IDragHandler {
  public override void OnBeginDrag(PointerEventData _) {}
  public override void OnDrag(PointerEventData pointerEventData) {
   // does not account for canvas scaling. you will have to deal with that
   transform.position += pointerEventData.delta;
  }
}
woeful leaf
polar marten
#

@woeful leaf that's it.

woeful leaf
#

I can try to implement it

#

Oh

polar marten
#

you can delete

#

all this other code

plucky inlet
woeful leaf
#

I thought Drag was for like mobile

polar marten
#

you don't need a collider

woeful leaf
#

I have one

polar marten
#

you shouldn't have colliders

#

if you're not using physics

woeful leaf
#

I am though

polar marten
#

what does @woeful leaf mean by physics?

#

it isn't going to change the correctness of this script

woeful leaf
#

It has a rigidbody

polar marten
#

okay

#

are you using physics?

#

not sure

woeful leaf
#

Yeah it uses the velocity of the rigidbody

#

And the collision to collide with other objects

polar marten
#

i think you are at the start of a very long journey

woeful leaf
#

;-;

polar marten
#

what is the game?

plucky inlet
#

Oh did not know you can use OnDrag on UI, because it acts like a "collider" already, thanks ๐Ÿ™‚

polar marten
#

in order for an object to receive OnDrag calls it must also have OnBeginDrag, which is a code smell of this api

plucky inlet
#

But well, here you have your solution @woeful leaf just use doctorpangloss code with your positioning of recttransform ๐Ÿ™‚

polar marten
#

it really depends what the game is

woeful leaf
#

Let implement it and see what it does

polar marten
#

@woeful leaf
there are three ways to move objects:
1 by changing their transform's position
2 when an object has a rigidbody, moving it kinematically (its velocity is derived at the end of the frame)
3 when an object has a rigidbody, moving it with forces (its velocity is natural)

when you want to move an object naturalistically using the pointer, and the object has a rigidbody, and you want the rigidbody to behave physically and naturalistically (#3), you can use joint drives between the rigidbody and an object whose position is being changed by the pointer's delta

#

#3 is really complex but you can find a lot of examples online

woeful leaf
#

Although 3 would be cool to implement, it is not needed, nor do I have the time to implement it. And I don't even know if it'd fit the game heh

#

Currently it's just 1.

polar marten
#

@woeful leaf what is the game?

#

well #1 doesn't work if you want physics

woeful leaf
#

I know but I don't have like very "real" physics

#

The only thing that it has is a collider and a set velocity on the rb

polar marten
#

you are doing #2 then

woeful leaf
#

And also 1.

plucky inlet
#

You can still use the transform.position, if you want to ignore phsyics while dragging. So, I do not think its for us to determine your game here ๐Ÿ˜„

woeful leaf
#

When you grab an object it uses the transform

#

But when it falls it uses rb.velocity

polar marten
#

okay

#

dragging objects around with a pointer in a general sense is hard

#

since you don't need a general solution, if you can tell me what the game is, i can make a specific suggestion

#

just eyeballing it, there's a lot that's sort of flawed about how you architected your game

woeful leaf
#

:(

polar marten
#

@woeful leaf here's an example of this dragging script in action
https://appmana.com/watch/theheretic
you can try moving around the lights, flicking them, rotating the camera, and if you visit on mobile, you can use multi touch

woeful leaf
#

public override void OnDrag(PointerEventData pointerEventData) {
// does not account for canvas scaling. you will have to deal with that
transform.position += pointerEventData.delta;
This appears to banish the objects to the shadow realm

polar marten
woeful leaf
#

It's quite a simple game really. You've these passwords that fall down, the passwords that are bad you put in the red box, the ones that are good you put in the green box

polar marten
#

okay

#

attaching rigidbodies to ugui elements typically does not work very well. it requires understanding way more nuances than you will comprehend. let's pretend the rigidbodies don't exist, since for now, other than for the dropping physical effect which is easy to do in code, you don't need them.

1 set your canvas to screen space overlay
2 then use the script i provide

#

if you want to use screen space - camera, you can try transform.localPosition += pointerEventData.delta, but i feel like i am just programming this for you and you don't really comprehend yet a lot of stuff

#

so it really depends what your goals are

polar marten
woeful leaf
#

I've two canvases

polar marten
#

okay well

woeful leaf
#

One is for the passwords

polar marten
#

i think you'll figure this all out

woeful leaf
#

The other is for the rest

polar marten
#

i think you can google "dragging sprites unity physics" and you should probably not use canvases at all. you can use TextMeshPro Text (not the UGUI version) to make the text labels

#

then it will be more intuitive for you

#

transform.localPosition will resolve your issues with pointerEventData.delta in this case

woeful leaf
#

I made like everything without googling except the IPointer events cuz OnMouseOver didn't work

polar marten
#

OnMouseOver is deprecated

nocturne zenith
#

is it possible to make y = 0 while keeping the same rotational axis? on a quarternion

woeful leaf
#

It matches the position instead of yeeting it somewhere3 else

polar marten
#

for that matter so is Input.GetMouseDown

woeful leaf
woeful leaf
polar marten
#

the pointerEventData is giving you all the information you need about the pointer

woeful leaf
#

Anyway thanks for all the help, I'll go expirement a bit with the OnDrag and see what that does for me

vestal oriole
#

Does anyone know if it is possible to convert a .texture2d file to an exr file? Thanks

verbal grail
#

Can someone give me a quickie? If I have a worldSpaceMatrix and an offsetMatrix, and I want to subtract the offset, is it as simple as worldMatrix * inverse(offsetMatrix)?

vestal oriole
main shuttle
graceful patio
#

.env unity?

#

yk .env file

vestal oriole
main shuttle
wicked wagon
west elk
#

Hi, does OnEnable gets called every time the object is set active?

west sparrow
#

Yup

whole yew
#

guys I have a question,

button.onClick.AddListener(() => DoSomething(CalculateSomething()));

If add a listener to a button like this, which calls a function, and "CaluclateSomething" will return some sort of value. Will the value that is return from CalculateSomething be called when the button is clicked or when the listener is assigned?

woeful leaf
#

When it is clicked

#

Adding a listener won't execute the method

#

Only whenever the listener is called