#archived-code-general

1 messages · Page 178 of 1

gray mural
#
[Serializable]
public class Property<T>
{
    [SerializeField] private T _value;

    public T value
    {
        get => _value;
        set => _value = value;
    }

    public static implicit operator T(Property<T> @this) => @this.value;
}
somber nacelle
#

by definition that no longer makes it an auto property and would therefor require being a full property with an explicit backing field

plucky fulcrum
#

Enabling opaque textures in urp makes everything in the game completely black

#

why

somber nacelle
#

this is a code channel

lucid valley
#

[field: SerializeField]
public int x { get; private set; }
gray mural
#

anyway, it won't work if I do like this:

[field: SerializeField]
public int x
{
    get;
    set => Debug.Log("works");
}
lucid valley
#

no, as thats no longer an auto property

gray mural
#

still need an additional field

gray mural
#

as it's usually done in e.g. OnValidate

knotty sun
mild karma
lucid valley
#

^

leaden ice
gray mural
#

sounds hard

#

I just should call a public method when changing a field

gray mural
#

it should be modified though

leaden ice
leaden ice
knotty sun
gray mural
#

a method is better in this example.

somber nacelle
#

an autoproperty cannot have validation code

knotty sun
#

that is different, not the reason given

mild karma
#

Not that it’s wrong

knotty sun
#

yes, I'm being pedantic, but, hey, this is programming, pedantic rules

broken light
#

so I have this in my editor script:

        SerializedProperty _meshes;
        void OnEnable()
        {
            _meshes = serializedObject.FindProperty("_meshData");
        }
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            Debug.Log(_meshes.arraySize);
        }

and in my scriptable object i have:

        [SerializeField]
        Mesh _meshData;

Yet it doesn't seem to work as I get this error Retrieving array size but no array was provided

What am i doing wrong here?

leaden ice
broken light
#
Retrieving array size but no array was provided
UnityEditor.SerializedProperty:get_arraySize ()
MeshDescriptorEditor:OnInspectorGUI () (at Assets/Editor/MeshDescriptorEditor.cs:17)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
leaden ice
#

In fact clearly it's not

broken light
#

oh shit

leaden ice
#
        [SerializeField]
        Mesh _meshData;```
#

it's a Mesh

broken light
#

oops

#

i forgot 😄

#

thanks for that

elfin tree
#

Does a Camera.gameObject that is .SetActive(false) use a non-negligible amount of resources?

knotty sun
lean sail
rigid island
#

2 cameras is quite expensive

elfin tree
elfin tree
knotty sun
lean sail
# rigid island huh?

That was under the assumption only 1 was on at a time yea since they said setting it inactive

broken light
#

how do i get my custom struct out of my serialised property ?

#

i got :
var descriptor = _meshes.GetArrayElementAtIndex(i);
then
var test = descriptor.managedReferenceValue as MyStruct;

#

but that doesn't work

#

i cant figure out how to do it for structs

green radish
#

How might someone add a description like this to a custom datatype?

rigid island
green radish
#

tried this and there's still no description when hovering over the datatype

#

and removing the /// makes the code invalid

#

oh wait I think I see what the problem might be

#

nevermind, still nothing

#

I thought maybe it was changing the second <summary> to </summary>

#

but that didnt change anything as it stands

green radish
#

so it should go above the thing it's a summary of, like this?

rigid island
green radish
#

ah

rigid island
green radish
#

still not getting a description for some reason

rigid island
green radish
#

yes

#

saved, went over to a script that was using it as a test, hovered and screenshot

rigid island
rigid island
#

idk

#

what version you using ?

green radish
#

I reformatted the line to be /// <summary>Test.</summary> to be more space efficient

#

rather than three lines

rigid island
#

should work fine

green radish
rigid island
#

anything xml in /// should be valid afaik

rigid island
green radish
#

oh sorry, thought you meant Unity

rigid island
#

unity is irrelevant here lol

green radish
#

Visual Studio 2022

#

which should be the latest one as far as I know

rigid island
#

yes ur good

hard viper
#

I have a physics-related code concern. I put the equivalent of 100 goombas on the screen. They send collision callbacks, but do not send force. If they all overlay, my framerate plummets because I get 100^2 onCollisionStay callbacks. Are there any usual approaches to this?

hard viper
#

Assume I made a very light but necessary OnCollisionStay(), and I cannot stop the player from putting 100 goombas into a little hole

rigid island
#

OnCollisionStay iirc runs similiar interval FixedUpdate?

#

i could be wrong tho

hard viper
#

mostly, if enemy is overlaid with something that should hurt it, kill the entity

#

sould send messages

#

because it's a generic script, that would also handle something like a fireball

rigid island
#

onstead of using OnCollision stay you use oncollision enter? or triggers ?

green radish
# rigid island restart VS? lol

wasnt necessary, I figured out that the problem is that, for some odd reason, if you have a line making the datatype serializable, the summary must be above that, or else Visual Studio throws a fit and refuses to acknowledge its existence

rigid island
#

yeah it probably thought you wanted to try to Serialize the summary or something

hard viper
#

but it needs to do that 10,000 times per frame

rigid island
hard viper
#

that line where we check twice speeds everything up by 2x, because those Actions are null. and they are null every frame.

#

if I could, I would just block out that whole function if both Actions are null, so it doesn't need to check OnCollisionStay every frame.

green radish
#

order of opperations and all that

tepid brook
#

Hi guys i have sometime a problem when i check if something is null and when i put an item in the current array there is no erreur like that

if (inventory[i].item != null)
{
  slot.GetComponent<InventorySlot>().AssignItem(inventory[i]);
}    
#

yep

#

but sometime its working so i don't understand ahah

rigid island
#

slot could also be null or you don't have InventorySlot on it

tepid brook
#

no its every time null

rigid island
#

use debugger 🙂

tepid brook
#

i've change to
if (inventory[i] != null)
and im gonna see if its working every time

#

i check if there is an item or not in the list but when i start the game to test the chest is empty so it null every time

lean sail
tepid brook
terse garnet
#

guys, how can i make a dash movement on mobile? on desktop i'm taking the mouse direction to direct the dash, but how can i do that on mobile?

rain minnow
terse garnet
#

i tried but not worked

#

I will show

rain minnow
#

Is it similar to your previous code for the mouse? I guess we'd have to see exactly how you dash . . .

misty jasper
#

Hey if possible I could use some help with the input system rn

#

it's bugging out on me and I dunno how to fix it

terse garnet
#

like this?

#

function Dash

rigid island
cosmic rain
#

No. That doesn't explain what you try to achieve. It explain what I already know.

hard viper
#

i guess I’m wondering how Mario maker can let you have 200 goombas on one square, and the game doesn’t chug

rigid island
#

dozens of smart engineers who know their own engine

hard viper
#

maybe I need to split enemy collision callbacks between enemies and non-enemy entities?

#

then goomba raycasts forward to see if it needs to turn

#

idk is 200 raycasts per frame viable? or too much for unity?

#

or maybe a trigger collider? but idk if a trigger collider with 200 things in it will also give me 200^2 callbacks if everything is in a blob

plucky karma
night harness
#

@hard viper atleast for goombas, you wouldn't need to actually know it hit a wall. just check if it moved more in that direction compared to last time it tried to move, if it didn't, turn it around

hushed notch
#

So I'm working through some of Valem's tutorials regarding hand presence, and we're putting these scripts on "Right Hand Model" etc. But, given that these scripts aren't referencing the parent game component directly, and simply have public fields to fill with scripts and references, is the placement of a script on a game object somewhat arbitrary in these situations?

plucky karma
#

I know it's possible to exclude plugins and foldier using .asmdef to say Exclude this plugin from building on specific platform. However, how can I exclude plugins and folder base on preprocessing directives? E.g.

#if FULL_GAME_ACCESS

// code will be used in full product but not use in any demo product

#endif
#

I don't want to go through all of the plugin scripts and manually add preprocessing directive, because then that would violates the plugin's term of agreement. (Cannot ship modified source code)

cosmic rain
cosmic rain
hushed notch
#

I guess my question is a little more meta than concrete; i have it all working.
But my question is more about in situations like this, could the "Animate Hand on Input" script be placed elsewhere yet still function with the correct references?

broken light
#

does any one know how to paginate my array of elements for a custom inspector such that it paginates before it creates a scrollbar ?

plucky karma
# hushed notch So I'm working through some of Valem's tutorials regarding hand presence, and we...

It depends. You can have a script that house reference to all of the appropriate game objects you wish to interface in code.

E.g. You can have a script that depends on the object you apply to

// this attribute will tell unity that any gameobject that have this script must have AudioSource, or unity will add them for you when you attach! (Note it does not assign when it is already attached to the gameobject before adding this attribute.)
[RequireComponent(typeof(AudioSource))]
public class MusicBox : MonoBehaviour {
  // because of the attribute, I will be responsible for the audio source.
  private AudioSource _src;
  // for whatever reason this object may be, Maybe I want it to move on sound source, but using this just an example of optional filler requirement.
  [SerializeField] private GameObject speakerGO;
  
  // awake is called before start - acquire component within itself.
  void Awake() {
    // I expect this gameobject to have AudioSource, or we'll have problems!
    _src = GetComponent<AudioSource>();
  }
  
  // start called after awake - acquire reference(s) outside this object scope.
  void Start() {
    // This guy could be null, but would prefer to assign something!
    if( !speakerGO && transform.childCount > 0 ) {
      speakerGO = transform.GetChild(0).gameObject;
    }  
  }
}
plucky karma
cosmic rain
plucky karma
cosmic rain
#

Builds don't affect the editor environment.

hushed notch
plucky karma
cosmic rain
hard viper
#

this just helps spread enemies out to avoid single death blobs with like 50 enemies

lapis ruin
#

(repost since i couldnt get this answered last time around)

Currently I have a whole Rigidbody based first person movement system, and the only problem with it is that it struggles to go up any drastic change in height such as a stair. To counter this, I want to make the player sort of always keep a .5 unit offset from the closest ground to their feet (so floating, pretty much) with the use of a Raycast detecting the ground below them. The way to do this would be to continuously change the Y of the player from the Y of the point of raycast collision plus that .5 unit offset mentioned previously by changing the player's transform. So I did this, it works fine. But is there any way I can fix the jittering?

let me know if my explanation of the whole thing is confusing

hard viper
#

what jittering?

#

you used a raycast to always keep a fixed distance from floor

leaden ice
#

A better approach would be to add forces as appropriate when on a slope to counteract the influence of the slope

#

Also if possible use a flat ramp collider rather than jagged stairs

lapis ruin
hard viper
#

i do a little bit of both. my rigidbody applies forces primarily to go along slope. but I also move transform directly very tiny distances if my collider gets disconnected from floor, which happens if “running off” a slope

#

but i don’t have stairs. only slope

#

moving my transform can work smoothly because it is only ever a very small correction, done infrequently

lapis ruin
#

you know what

#

fuck stairs, man

hard viper
#

that’s the spirit

#

just DRAW stairs

#

stairs.jpg

night harness
#

A majority of games don’t use real stairs like that for movement

#

its all collider ramps

leaden ice
#

Stairs are actually a really complex physical interaction

#

Not modeled well with capsule shaped people

hard viper
#

stairs are notorious for being hard as shit

night harness
#

Actual stairs are for visuals and if your fancy feet IK

lapis ruin
hard viper
#

stairs.png

#

apply texture

#

done

lapis ruin
#

I'm gonna keep messing around with that whole fixed distance from floor thing, see if i can change some things to stop the jitter and other problems im having with it right now

#

if not then

#

we'll have to fuck the stairs

#

not in that way but

#

im sure you get it

#

thank you all

versed condor
#

Does anybody know how to fix character controller sticking to cielings whn you jump?

leaden ice
#

Actually I guess you're probably simulating velocity yourself? I would just zero out the y velocity if you detect a collision with the ceiling

neon junco
versed condor
rigid island
#

nahh its this prob what Praetor said

leaden ice
#

You can use the collision normal to see if it was the ceiling. The normal will be facing downwards

hard viper
#

i agree with navarrone

#

rebrand to spiderman

rigid island
#

the next spiderman unity on mobile

cosmic ermine
#

Trying to do marching squares and I just can't seem to get my vertices and indices working. There is almost certainly a mistake in this method, but I can't work out what it would be. ```cs
public static SimpleMesh<Vertex,uint> GetMeshForSquareIndices(NativeArray<byte> SquareIndices, NativeArray<int3> Positions, float HalfWidth)
{
SimpleMesh<Vertex, uint> Mesh = new SimpleMesh<Vertex, uint>(Allocator.Temp, 8 * (uint)SquareIndices.Length, Allocator.Temp, 12 * (uint)SquareIndices.Length);

int VertIndex = 0;
uint IndexIndex = 0; // The worst name of any variable ever!

for (int i = 0; i < SquareIndices.Length; i++)
{
    byte SquareIndex = SquareIndices[i];
    int2[] Vertices = VertexTable[SquareIndex];
    uint3[] Indices = IndexTable[SquareIndex];

    for (int vi = 0; vi < Vertices.Length; vi++) // loops over vertices for the specific square index and adds them to the mesh
    {
        Vertex CurrentVertex = new();
        CurrentVertex.Pos = new float3(Vertices[vi], 0) * HalfWidth + Positions[i];
        Mesh.Vertices[VertIndex] = CurrentVertex;
    }

    for (int ii = 0; ii < Indices.Length; ii++) // loop over indices for the specific square index and add them to the mesh, with correct vert offsets
    {
        Mesh.Indices[ii + (int)IndexIndex] = Indices[ii].x + IndexIndex;
        Mesh.Indices[ii + (int)IndexIndex + 1] = Indices[ii].y + IndexIndex;
        Mesh.Indices[ii + (int)IndexIndex + 2] = Indices[ii].z + IndexIndex;
    }

    VertIndex += Vertices.Length;
    IndexIndex += (uint)Indices.Length*3;
}

return SimpleMesh<Vertex, uint>.FromRange(Mesh, 0, (uint)VertIndex, Allocator.Persistent, 0, IndexIndex, Allocator.Persistent);

}

sleek bough
#

You would probably want to put a breakpoint and examine step by step. I usually use async methods with gizmos to animate slowly and debug points visually as well.

cosmic ermine
#

Thanks I forgot breakpoints exist lol!

thick summit
#

Just tried to compile my first unity app and i'm hitting a breakpoint here.
How would I debug it for iOS?

leaden ice
#

looks like you are debugging it?

#

(from xCode)

thick summit
#

I mean like where its actually causing it. No such file without knowing a file is hard

2023-08-24 05:15:04.648672+0200 RadarGSI[50161:3578780] fopen failed for data file: errno = 2 (No such file or directory)
2023-08-24 05:15:04.648701+0200 RadarGSI[50161:3578780] Errors found! Invalidating cache...
2023-08-24 05:15:04.962671+0200 RadarGSI[50161:3578780] fopen failed for data file: errno = 2 (No such file or directory)
2023-08-24 05:15:04.962720+0200 RadarGSI[50161:3578780] Errors found! Invalidating cache...
leaden ice
#

you should use the visual studio / rider debugger for the C# code

thick summit
#

The code runs fine on mac and pc
Figured it was some xcode setting, but now I get this error

Assertion failed: 0 && "RuntimeType::get_DeclaringMethod", file ./Il2CppOutputProject/IL2CPP/libil2cpp/icalls/mscorlib/System/RuntimeType.cpp, line 751
void il2cpp_assert(const char* assertion, const char* file, unsigned int line)
{
    printf("Assertion failed: %s, file %s, line %u\n", assertion, file, line);
    abort();
}
unreal oak
#

hey guys, I was wondering if any of you know how to change how the camera in unity's scene view rotates? When I rotate I want it to go left and right from my perspective, but instead it spins my camera the other way. Pretty frustrating.

rigid island
unreal oak
#

oh my bad

rigid island
unreal oak
#

thank you

modern creek
#

If I want to do some drag-to-select stuff in my 2d game, should I draw the box and capture input in a UI layer object? Or is there a better way to do this? In the video above, "UiHud" has a GO called "InputCaptureImage" which is a 0% alpha image over the entire screen so I can capture pointer down/up/drag.

misty drum
modern creek
#

oh, that's a nice idea.. or I could even do both.. instead of the box, the tiles (in my example) or units, or whatever existed in worldspace .. could receive the "you've been selected" event

#

the box in world space could even be visible, so i wouldn't need to do anything in the UI layer at all

misty drum
#

im probably a worse programmer than you lool, i just do stuff that requires the least mixing of code lol

modern creek
#

it's a good idea, though

misty drum
#

i also used a line renderer for the box outline, make sit look nice

modern creek
#

as it is, I'd need to translate a lot of UI layer coordinates to world space coordinates

misty drum
#

yeah thats why im trying to do as much of the game a si can without a canvas

#

anythign that interracts with the world anyway

modern creek
#

my tentative plan was just to make a 9sliced image for this selection box, but i'm finding i'm already doing a lot of translation from UI space (scaled by canvas scale) to/from click space and to/from grid space

#

hm, the only problem i see is the selection volume might appear weird if you're zooming in/out..

misty drum
#
 private void SetLineRenderToBox(Vector2 startPos, Vector2 endPos)
    {

        //Sets position of each linerender line's vertex point
        lR.SetPosition(0, startPos);
        lR.SetPosition(1, new Vector3(endPos.x, startPos.y));
        lR.SetPosition(2, new Vector3(endPos.x, endPos.y));
        lR.SetPosition(3, new Vector3(startPos.x, endPos.y));
        lR.SetPosition(4, startPos);

        //Adjusts line's start and end width to stay the same width durring camera zooming
        lR.SetWidth(startLineWidth * (cameraMain.orthographicSize), startLineWidth * (cameraMain.orthographicSize));

        //sets sprite renderer gameobject(fillSprite) to center of select box, and scales it to touch the lines of the line renderer (rectangle only)
        fillSprite.position = (startPos + endPos) / 2;
        fillSprite.localScale = startPos - endPos;

    }
```fillSprite is just a gameobject with a sprite renderer and my collider
modern creek
#

oh manually drawing the box

misty drum
#
        //Adjusts line's start and end width to stay the same width durring camera zooming
        lR.SetWidth(startLineWidth * (cameraMain.orthographicSize), startLineWidth * (cameraMain.orthographicSize));
modern creek
#

hm... I'll have a think on this. I think there's pros/cons but it never occurred to me to do it directly in worldspace

misty drum
#

yeah my box is jsut a sprite that fills the positon between where ym mouse starts dragging, and where it currently is/ends being

modern creek
#

how are you capturing the initial click and startPos?

misty drum
#

uh, lemme check lol

#

i got soem messy logic in here for now while i test shit, but this

#
 //Sets initial Position of Drag Box if drag SHIFT operator key is pressed and mouse has been clicked down
        if (Input.GetKey("left alt") && Input.GetMouseButtonDown(0))//SHIFT  |  LMB
        {

            if (debugMode) { Debug.Log("Drag Down"); }
            selectStartPos = screenToWorld.MouseWorldPosition;
            selectEndPos = screenToWorld.MouseWorldPosition;

            selectionBox.SetActive(true);
            if (debugMode)
            {
                foreach (Ship i in selectedShips)
                {
                   i.VarSelectable.IsSelected = false;
                }
                selectedShips.Clear();
            }

        }

        //Sets Updated End Position of drag Box as long as LMB is held down
        while ((selectionBox.activeInHierarchy) && Input.GetMouseButton(0))//LMB
        {
            if (debugMode) { Debug.Log("Drag Hold"); }

            selectEndPos = screenToWorld.MouseWorldPosition;

            clickHeldTimer += Time.deltaTime;
            return;
        }

        //redundancy incase for some reason selection box is not active in hiarchy but click heldtimer is
        //Comes before ' "X" comment ' if statement below for Execution bug
        if (!selectionBox.activeInHierarchy && Input.GetMouseButtonUp(0))//LMB
        {
            clickHeldTimer = 0;

            selectionBox.SetActive(false);
            if (selectedShips.Count > 0)
            {
                foreach (Ship i in selectedShips)
                {
                    i.VarSelectable.IsSelected = false;
                    Debug.Log("LMB-UP Removing");
                }
                selectedShips.Clear();
            }
        }
        // "X"
        //Resets Drag Box if LMB mouse key unclicked
        if (selectionBox.activeInHierarchy && Input.GetMouseButtonUp(0))//LMB
        {
            if (debugMode) { Debug.Log("Drag Up"); }

            clickHeldTimer = 0;

            selectionBox.SetActive(false);
        }

modern creek
#

ah, yeah, I'm probably not going to go that approach (i'm assuming this is in an Update loop somewhere?)

misty drum
#

screenToWorld is my mini script for my whole project that translates mouse screen position to world position

#

all of this is inside a methdo that is insidea an update yeah

modern creek
#

this is OK though - I can grok this, it's good stuff, thanks

misty drum
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScreenToWorld : MonoBehaviour
{
    [SerializeField] private Vector2 mouseWorldPosition;
    public Vector2 MouseWorldPosition { get { return mouseWorldPosition; } private set { } }

    void FixedUpdate()
    {
        //sets cursor's canvas position to world vector2
        mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }

}

#
    //Sets all active selectables inside of fillSprite collider to selected if not already selected on highlight
    private void OnTriggerEnter2D(Collider2D col)
    {
        Ship i = col.GetComponent<Ship>();
        if (i.VarSelectable.IsSelectable)
        {
            i.VarSelectable.IsSelected = true;
            if (!selectedShips.Contains(i))
            {
                selectedShips.Add(i);
            }
        }
        var test = col.GetComponent<Carrier>();
    }

    //Sets all active selectables inside of fillSprite collider to selected if not already selected inside highlight
    private void OnTriggerStay2D(Collider2D col)
    {
        Ship i = col.GetComponent<Ship>();
        if (!selectedShips.Contains(i))
        {
            if (i.VarSelectable.IsSelectable)
            {
                i.VarSelectable.IsSelected = true;
                if (!selectedShips.Contains(i))
                {
                    selectedShips.Add(i);
                }
            }
        }

    }
    //Sets all active selectables exiting fillSprite collider to unselected
    private void OnTriggerExit2D(Collider2D col)
    {    
        if (selectionBox.activeInHierarchy && col.isTrigger)
        {
            Ship i = col.GetComponent<Ship>();
            i.VarSelectable.IsSelected = false;
            selectedShips.Remove(i);
        }       
    }
#

and i use the OnTrigger methods for drag box action

#

again, messy, cna be cleaned, but it works

modern creek
#

yup, got it.. and i'm assuming when you release, you call all those objects and IsSelected=false them

#

Yep, I got the concept, I just hadn't thought of using a collider and a worldspace box for a selection tool

#

it's good

misty drum
#

very helpful if youre just doign rts style stuff

modern creek
#

ya that's exactly what this is

misty drum
#

same D:

#

the drag in action

#

@modern creek last thing, if you use the lien renderer for an outline like i did, make sure the line renderer "SetPosition()" methods are called before your input, otherwise it wont update as you drag, idk why it does it, not bothered enough to care

modern creek
#

interesting, cool, thanks

#

I probably won't use a line renderer (we'll have assets for a dragging box/volume) but it's good to know nonetheless 🙂

misty drum
#

i dont like 9-slicing cuz i have camera zoom

#

so i like to set the width of the lines with line renderer

#

thats the downside of it being in world space

modern creek
#

aye - it's a point in favor of doing it in the UI layer, or in some combination of UI layer + world space

#

in general I don't render stuff myself.. we have artists for that 😉

misty drum
#

im just saying, if you got camera zoom, your box outline will feel weird without scaling

#

hense i chose linerenderer

night harness
#

how would i get the sprite off a texture2d?

misty drum
#

spriterenderer.sprite

#

oh, texture

dusk apex
night harness
#

I'm doing it through code

misty drum
#

you tryign to null the variable, or add something into it?

dusk apex
#

Do you see any field for Sprite? No.

night harness
#

Yeah I'm aware mate, that's why I asked the question 😄

dusk apex
night harness
#

No but like, it does

misty drum
#

pic?

night harness
#

Unless I'm misunderstanding something

misty drum
#
A Sprite is an image that can be used as a 2d object, which have coordinates (x, y) and which you can move, destroy or create during the game. A Texture is also an image, but that will be used to change the appearence of an object.
night harness
#

?

misty drum
#

youre using an image as a texture, not as a sprite

night harness
#

I don't believe so?

misty drum
#

are you trying to like, convert a texture into a sprite?

dusk apex
#

Are you trying to create a sprite?

night harness
#

Both, I'm trying to get a reference of the sprite from it's Texture

misty drum
#

you cant do that at runtime

night harness
#

Why

misty drum
#

int he editor, you use an image, to create a 2D texture, that 2D texture is its own thing converted from an image.

#

you can make a painting with paint, but you cant make paint with a painting type of thing

night harness
#

But are sprites not saved as Texture2D's?

dusk apex
#

There are no sprite properties to be extracted

misty drum
#

if i rememebr technically no, you can convert a texture2D to a sprite, but you cant refference the original image and change it to change the texture

night harness
misty drum
#

in the editor

#

you got an example of what youre trying to do?

dusk apex
#

Else the assets should be in your project directory

night harness
#

Doing some code to ref. the right sprite asset I want depending on context

misty drum
leaden solstice
#

Multiple sprites can use same texture, thus finding sprite with texture does not make sense for general API.

#

You can build own Dictionary if that really is usecase

copper star
#

Does anyone know how I can offset a vector3 to be perpendicular to rigidbody rotation

#

currently my object moves left of the direction it is facing

dusk apex
copper star
# dusk apex Show your implementation of move

Oh thanks for responding, I realised I'm actually an idiot and my Vector3 was all in the X direction rather than Z, which is what I needed. However I got the jittery physics movement so I decided to try AddForce instead

swift falcon
#

How the IPointerHandle works? Like how does it get Invoked?

#

I thought interfaces just a contract that says "You need this method."

cosmic rain
tough ravine
#

can anyone reccommend a good tutorial on making sprites on blender

lean sail
tough ravine
#

alright thanks

#

just got into unity

#

pretty cool stuff

gray mural
#

How did they do in TMP_Dropdown so that the the method is called when value is changed in the inspector if they don't have OnValidate method?

#

So my goal is to do the same as they have done in my code

gray mural
cosmic rain
tired elk
#

TMP_Dropdown has an onValueChanged event IIRC, and the custom drawer is probably listening this

gray mural
#

I see

#

I'ma do it with OnValidate then

#

thanks for your reply 😄

bitter laurel
#

Hello everyone. Today I ran into a problem. I have a LeaderboardManager with Leaderboard (Script) attached to it, and it is on my first scene. It worked normally until I changed to the second scene and went back to the first scene, then I got this error:
Then I checked the GameObject, and I still saw my LeaderboardVisual attached to it:
In detail, I have a code block in my PlayfabManager, which is DonDestroyOnLoad:

    {
        Debug.Log(OnGetLeaderboardSuccess.GetInvocationList().Length);
        var request = new GetLeaderboardRequest
        {
            StatisticName = "Star",
            StartPosition = 0,
            MaxResultsCount = 30,

        };
        PlayFabClientAPI.GetLeaderboard(request, result => OnGetLeaderboardSuccess?.Invoke(this, new OnGetLeaderboardSuccessEventArgs
        {
            result = result
        }), error => OnPlayfabErrorEvent?.Invoke(this, new OnPlayfabErrorEventArgs
        {
            error = error
        }));
    }```
#

In Leaderboard - which attach to a game object that not have DontDestroyOnLoad, I have this to handle event fromPlayfabManager:

    {
        Debug.Log("Got the data from playfab:" +e.result.Leaderboard);
        playerLeaderboardEntries = e.result.Leaderboard;
        Debug.Log($"Entry count: {entries.Count}");
        if(entries.Count > 0)
        {
            for(var i = entries.Count - 1 ; i >= 0 ; i--)
            {
                PoolUILeaderboardEntry.Instance.ReturnToObjectPool(entries[i]);
            }
        }
        entries.Clear();
        for(var i = 0 ; i < playerLeaderboardEntries.Count ; i++)
        {
            UILeaderboardEntry entry = PoolUILeaderboardEntry.Instance.GetFromObjectPool();
            entry.SetLeaderboardEntry(playerLeaderboardEntries[i]);
            entries.Add(entry);
            entry.transform.SetAsLastSibling();

            //Check for leaderboard delay
            //if(playerLeaderboardEntries[i].PlayFabId == UserAccountManager.playfabID)
            //{
            //    if(leaderboard[i].StatValue != UserProfile.Instance.highscore) UserAccountManager.Instance.GetLeaderboardDelayed("Highscore");
            //}
        }

        //leaderboardVisual.Show();
        Debug.Log("Leaderboard Visual ID: " + leaderboardVisual.GetInstanceID());
        Debug.Log("This is the craziest thing i ever seen");
    }```
#

Now when I run my game for the first time, it worked perfectly. But when I switch to second scene and go back to the first scene, it shows the error.
Debug when error occurs, I have 2 Leaderboard Visual ID: One negative and one positive
And if an switch to second scene and go back to the first scene again, i the 3 Leaderboard Visual ID
So I'm thinking that the problem might be in the event part when there are 3 instances listening to that event.
How can I fix that 😦

potent saffron
#

Could you show us a screenshot of your DontDestroyOnLoad scene hierarchy? I think i might know what is happening

bitter laurel
potent saffron
#

Your leaderboardmanager is getting destroyed on scene change, and from what i assume, your playfabmanager needs a refference to it. Either make your leaderboard manager part of DontDestroyOnLoad using a singleton pattern, or program a function to get the refference on scene changes

bitter laurel
#

Yeah im thinking about making LeaderboardManager be DontDestroyOnLoad, but... I really don't want to do that because my second scene doesn't need to use that. And I think PlayfabManager doesn't need to have a Leaderboard reference, because it only Invoke an event when it gets leaderboard data from Playfab. I think the problem is when I come back to the first scene from the second scene and PlayfabManager Invoke the event, I have 2 event subscribers to that. The first one is the first Leaderboard when I start the game, the second one is the Leaderboard when StartScene is loaded again. The proof is at Debug.Log("Leaderboard Visual ID: " + leaderboardVisual.GetInstanceID()); , it shows me 2 results: Leaderboard Visual ID: -1344 and Leaderboard Visual ID: 100122.
According to what I read from Unity document here: https://docs.unity3d.com/ScriptReference/Object.GetInstanceID.html
I'm pretty sure there are 2 Leaderboards that exist when the error occurs.

#

And the other proof is, when I modify Playfab_OnGetLeaderboardSuccess function, with this:

        {
            leaderboardVisual.Show();
        }
        else
        {
            Debug.Log("It should not be shown");
        }

If only one Leaderboard exists, it should show the log: "It should not be shown" but I got the LeaderboardVisual show up, and that log too.

tired elk
bitter laurel
tired elk
bitter laurel
#

yeah. Leaderboard is sub and Playfabmanager is pub

tired elk
#

How do you do your subscription in the 1st place ? with a += ?

graceful latch
#

i have a first person camera system setup with the new input system and its jittery and i cant figure out why controls.player.mouselook is a vector 2 set to mouse delta

using System.Collections.Generic;
using UnityEngine;

public class MouseLook : MonoBehaviour
{
    [Range(0f, 100f)]
    [SerializeField] float mouseSensitivity;
    public InputMaster controls;
    [SerializeField] Transform playerBody;
    float xRotation = 0f;

    [Header("Clamp")]
    [SerializeField] float minClamp;
    [SerializeField] float maxClamp;

    private void Awake()
    {
        controls = new InputMaster();
        Cursor.lockState = CursorLockMode.Locked;
    }
    void OnEnable()
    {
        controls.Enable();

    }
    void OnDisable()
    {
        controls.Disable();
    }
    
    void Update()
    {

        float mouseX = mouseSensitivity / 100 * controls.Player.MouseLook.ReadValue<Vector2>().x;
        float mouseY = mouseSensitivity / 100 * controls.Player.MouseLook.ReadValue<Vector2>().y;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, minClamp, maxClamp);

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);
    }
    
} ```
bitter laurel
tired elk
#

Then, do the same in OnDisable, but replace += with -=

gray mural
#

is there any way to set a default parameter for T ?

public class OptionSelectionField<T> : MonoBehaviour where T : Component { }

public class OptionSelectButton<T> : MonoBehaviour where T : Component { }
#

or do I have to create an overload?

bitter laurel
gray mural
tired elk
gray mural
bitter laurel
#

I've just learned Unity & C# for about 3 months, so there are lot of things i didn't know

tired elk
# gray mural yes.

You'll need to define a proper class that inherit your generic unfortunately

bitter laurel
# gray mural yes.

you can do that, which i found on internet:
public class OptionSelectionField<T> : MonoBehaviour where T : Component
{
// Default value of T is set to Transform
private T selectedOption = default(T) ?? (T)(Component)(Transform)null;
}

gray mural
#

I have to make it work like that: OptionSelectionField field;

#

without <T>

#

but ofc it throws an error

#

so I have to do OptionSelectionField<Button> field

#

that's annoying.

#

anyway.

tired elk
#

You just want a default behaviour ?

#

Or is it to gain something like time typing ?

gray mural
#

as you may understand, I have fixed it using this method:

public class OptionSelectionField<T> : MonoBehaviour where T : Component { }

public class OptionSelectionField : OptionSelectionField<Button> { }
gray mural
gray mural
#

it's more comfortable when I don't have to specify a T

quartz folio
potent scarab
#

any way to let unity support opengl 2.0? (android)

gray mural
#

there isn't, yes

tired elk
#

You also can do this using IntNode = Node<int>; I think (from what I could find on internet)

gray mural
magic harness
#

Hello guys.
I'm making some AI for my enemies, and i thought i would be a really cool idea to have a MonoBehaviour that instanciates a regular C# object for the enemies Behaviour. The C# object would be serializable of course and it would be easy for someone to change behaviour specific variables on the inspector for the MonoBehaviour script.

so.. for instance:

public enum Behaviour
    {
        Chase, Patrol
    }
    [SerializeField] private Behaviour behaviour;
    [SerializeField]private AIBehaviour currentBehaviour;

private void SetBehaviourSpecificData()
    {
        switch (behaviour)
        {
            case Behaviour.Chase: currentBehaviour = new FlockLikeChaseBehaviour(); 
                break;

            case Behaviour.Patrol:
            default: break;
        }
    }

So basically it means running the SetBehaviourSpecificData function in Edit Mode, is it possible to do something like this?

barren stag
magic harness
steady moat
# magic harness Hello guys. I'm making some AI for my enemies, and i thought i would be a really...

Usually, behavior are made with a graph of ScriptableObject.

Also, note that you cannot use SerializeField for polymorphic class. You need to use SerializeReference (And you need to have an editor tool to be able to manipulate it as Unity as no built-in tool. Something like https://github.com/mackysoft/Unity-SerializeReferenceExtensions)

Finally, the pattern you are using at the moment is called Strategy Pattern. There is a ton of resources online on how to implement it in Unity. https://www.google.com/search?q=unity+strategy+pattern&oq=unity+Strategy+Pattern&aqs=chrome.0.0i512.5768j1j7&sourceid=chrome&ie=UTF-8

magic harness
stone scaffold
#

Hello,
I have made a common "Enemy" script assigned to an enemy where if the player is inside a trigger which is above the enemy, the enemy will not move. When I add multiple enemies into the scene with the same "Enemy" script, it works fine except when the player is above one enemy, all other enemies will also not move. How can I fix this?

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.

stone scaffold
#

would you like the entire enemy code or just that specific part?

stone scaffold
#

ok, it is over 100 lines of code tho

steady moat
quartz folio
#

Read the bot's message

stone scaffold
#

ohh

steady moat
#

We will need the player script as well.

stone scaffold
#

the trigger checks are at the bottom of each

magic harness
#

in the enemy script, the isAbove function is checking if the player's is in a trigger, any trigger

steady moat
stone scaffold
#

isAbove() checks if the player is in a trigger

magic harness
#

exactly

steady moat
#

You want to do the check on the enemy side

stone scaffold
magic harness
#

make isAboce return istouching, as an example

steady moat
magic harness
#

or just erase it and check IsTouching alone

stone scaffold
#

ah

#

so i would have to make another trigger function?

magic harness
#

does the trigger have any other functionality?

stone scaffold
#

one is for isTouching and the other is for isAbove

#

they are both in a separate layer so they dont collide

magic harness
#

seems to me like you're making this harder than it should be on yourself.
But yes, you can make another function for the isAbove trigger

stone scaffold
#

i'll see what i can do

#

thanks

#

but yes, first time coder here

magic harness
#

thats pretty good for a first time, keep it up!

proven path
#

In programming the pattern to program towards interfaces is very popular, but should I also use it in unity, or in other words, should I try creating an interface for every class that may be accessed in code, so that the class can be accessed via an interface, even if I could as well use the class type instead?

tired elk
proven path
spring flame
#

I can't wrap my head around sub assets, scriptable objects of custom type and custom asset importers.
I want to have:

  • a custom class Graph that is [Serializable] (but contains non-serializable data such as HashSets, so I have to somehow serialize it yet I don't know how for now) (Already have that)
  • an asset of type something.graph which holds Graph class instance and sub-assets material.mat and shader.shader. It should serialize the material and shader
  • when I create the asset (scriptable object has [CreateAssetMenu]) I want to create sub-assets for material and shader
  • I want this asset to display like that in the assets:
#

How do I do that?

spark stirrup
#

Assets\Scripts\PullPlayer.cs(9,13): error CS0246: The type or namespace name 'PlayerMovement' could not be found (are you missing a using directive or an assembly reference?)

public PlayerMovement movement;

What am I doing wrong?

spark stirrup
tired elk
#

I assume yes, but where is it defined ?

spark stirrup
#

This is defining it i thought:

public PlayerMovement movement;

swift falcon
#

Does that script exist

spark stirrup
#

Yes

swift falcon
#

Well I would check again because it cant find it

spark stirrup
#

I litterally have it open rn lol

tired elk
#

It declares a variable of type PlayerMovement, ok, but where do you define this class ?

spark stirrup
#

Ohh the class? it's defined in the player movement script:

public class PlayerMovement : MonoBehaviour

tired elk
#

Do you have any other compilation error in your console ?

spark stirrup
#

Nope

tired elk
#

Is PlayerMovement a class you defined yourself or is it from a package ?

spark stirrup
#

It was a script from the first person template that I renamed

tired elk
#

Did you rename the file as well ?

spark stirrup
#

Yes

tired elk
#

Is it contained in a namespace ?

spark stirrup
#

Yes, but I tried doing:
using StarterAssets; and that didn't change the error at all

tired elk
#

Is by any chance this scripts stored in a folder called StandardAssets ?

spark stirrup
#

Nope, it's in a folder named Scripts

tired elk
#

can you share the !code of PlayerMovement please ?

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.

tired elk
#

Yeah you have the right namespace and all

#

I'm kinda out of idea here

#

Try closing and reopening unity, sometimes errors are hidden and show after a restart

spark stirrup
#

Yeah i have no idea. I'm referencing another script the exact same way in my script with no issues

#

Alr lemme try that

#

Nope still there

vague sedge
#

im trying to use customize unitys character controller to walk smoothly on any surface, at the moment ive ran into an issue where the character has no problem walking along the worlds z axis but when walking along the x axis as soon as the player hits 180 degrees the x axis input inverts and im not sure how to fix this, i was hoping if i sent someone my code maybe they could have a glance at it or just any advice would help

https://gdl.space/nujuwiseli.cs

spark stirrup
tired elk
#

That's weird, but fine

steady moat
vague sedge
tired elk
#

If you did StarterAssets.PlayerMovement it should work fine

#

Anyway, you fixed it and it's the most important

steady moat
spark stirrup
#

I tried dragging the player with the script attached into the variable slot but I can't

tired elk
vague sedge
spark stirrup
steady moat
tired elk
rain minnow
spring flame
# steady moat https://docs.unity3d.com/ScriptReference/AssetDatabase.AddObjectToAsset.html

I have read it, but I want to create fresh shader and material when asset is created. Should I be doing it in the OnEnable of my ScriptableObject, or maybe I should avoid using [CreateAssetMenu] and use [MenuItem("AssetDatabase/...")]? But then when I write a ScriptedImporter where do I assign the shader and material to the asset? I can't conceptually grasp what the main object of the asset is and how I write some serialization/deserialization for that

spark stirrup
tired elk
# spark stirrup

Is it the right PlayerMovement ? Like, if you double click it, is it the script you shared earlier ?

spring flame
rain minnow
steady moat
vague sedge
spring flame
#

just like shadergraph asset has it's own material

steady moat
#

There is nothing else to do.

#

Something like that

MyObject.Shader = myAsset;
AssetDatabase.AddObjectToAsset(MyObject, myAsset );```
spring flame
#

oh, so I don't need to create material and shader with the AssetDatabase, just use new Material() and add it to the asset?

steady moat
#

new Material() is only memory.

spark stirrup
tired elk
#

I'm puzzled, but glad you fixed your issue

spark stirrup
heady iris
#

these problems don't make sense. Something else is wrong.

short ferry
#

don't know if i'm in the right thread but, my level looks fine in blender but when putting the same file in unity a lot of textures don't show, there are some visual glitched etc as you can see. someone help pls?

short ferry
#

what is the right thread?

vagrant blade
rigid island
vagrant blade
#

Also check for flipped normals

tired elk
short ferry
#

tbh don't even know what that means, i'm kinda new to 3d unity

vagrant blade
#

I was just linking the fact I mentioned it.

steady moat
#

@swift ocean

What happens if you find in a position where your randomly generated map cannot fit the constraint you made ?

modest thicket
#

Wave Function Collapse / Other procedule generation methods -> Thread

scarlet juniper
#

so i have this piece of lines where i get the 4 audioclips from the resources folder however when i play only the first one is found. Spelling is correct, paths are correct. once i disable the first line then only the second one is found. any knows what is causing this?

leaden ice
scarlet juniper
#

disabling as a check so '//'

#

so it becomes green, just to check it

#

running the code in update

leaden ice
leaden ice
#

or if you're hardcoding the paths anyway, why not just directly reference the things in serialized fields?

#

Anyway what makes you think it's not finding the others after the first?

scarlet juniper
#

i did it in start and awake but then it finds none

#

not even the first one

scarlet juniper
leaden ice
scarlet juniper
#

because it finds none

leaden ice
#

how do you know it finds none

#

how are you checking

scarlet juniper
leaden ice
#

How does this make the inspector cleaner

#

you can just assign them here

scarlet juniper
#

yes and i want to get rid of them

leaden ice
#

ok so

#

show the code

#

the full script

scarlet juniper
#

oh gosh

leaden ice
#

probably some other code is unassigning them

#

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

leaden ice
#

My moonshot theory - you have something like if (WeaponShoot = null)

scarlet juniper
#

ye im using pastebin is that fine?

leaden ice
#

yes

scarlet juniper
#

please dont hate on my coding style im trying to clean some up rn lmao

leaden ice
#

that's not pastebin

scarlet juniper
#

huh

leaden ice
#

I'm on a work computer can't download files really

#

so I can't read that

#

please post to a paste site

scarlet juniper
#

you cant expand that?

leaden ice
#

it only shows some lines

#

not the full file

scarlet juniper
#

oh how can i do it otherwise?

leaden ice
#

!CODE

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

scarlet juniper
#

ive always used that

leaden ice
#

literally the same thing

#

please upload to a paste site

#

not to discord

scarlet juniper
#

like the link?

leaden ice
#

upload to the paste site and share the link here, yes

scarlet juniper
leaden ice
#

yes

#

thank you

scarlet juniper
#

well thats a new way

leaden ice
scarlet juniper
#

correct

leaden ice
#

Can you try:

WeaponShoot = Resources.Load<AudioClip>("WeaponFolder/Audio/RetrofitEscapadeFire1");
WeaponAimIn = Resources.Load<AudioClip>("WeaponFolder/Audio/RetrofitEscapadeReload3");
WeaponAimOut = Resources.Load<AudioClip>("WeaponFolder/Audio/RetrofitEscapadeReload1");
WeaponReload = Resources.Load<AudioClip>("WeaponFolder/Audio/RetrofitEscapadeReload7");

if (WeaponShoot == null) {
  Debug.Log("WeaponShoot is null");
}
if (WeaponAimIn == null) {
  Debug.Log("WeaponAimIn is null");
}
if (WeaponAimOut == null) {
  Debug.Log("WeaponAimOut is null");
}
if (WeaponReload == null) {
  Debug.Log("WeaponReload is null");
}```
scarlet juniper
#

sure

#

i have no one clue of what you changed

#

but somehow it finds all of them now

#

you littarly used debugs and it works what the hell

leaden ice
#

maybe it was an issue of the script not being saved? IDK

scarlet juniper
#

i been trying this for the past hour, and have changed and saved this many times

#

i removed the debug and the lines are on the exact same spot

#

and now they are all found

#

thanks for the help!

#

as always

#

🙂

scarlet juniper
#

yes i will next time upload the link for everyone : )

heady iris
#

if it weren't for this, it'd be a very nice way of sharing large code files

#

alas,

leaden ice
#

don't crosspost

modern creek
#

If I want a prefab that exists in world space (a sprite renderer) but I want some components on it to be rendered in UI space (like a slider or some text).. how would I do that?

#

(When I try to create a UI element on a non-canvas prefab, it adds a new canvas to the prefab)

#

worldspace text..?

#

I've put a canvas on my prefab and a text under that, but it doesn't show up in the scene (and I can't do layout in the prefab editor since it's in UI scale - ie, it's huge relative to my sprite)

#

i get one of these things where the sprite is tiny in the lower left

#

and the text doesn't render at all in the scene:

#

If I have to make two separate prefabs, one that's the "world" prefab and another that is the "UI" prefab (to show things like hitpoint sliders, name of the unit, etc) I can do that, but that seems like it's the wrong way to do it

timid meteor
#

quick question I am getting this error in my code. error CS0117: 'Noise' does not contain a definition for 'GetNoiseMap'. (here is the line for the code) noiseMapTexture = Noise.GetNoiseMap(width, height, scale); Does unity not have a base Noise? Do I need a using for it?

modern creek
#

I have it working if I set the canvas size (on the prefab) to 0 and the tmpro size to world space size.. but this leads to font sizes in world space, which is .. odd. Is this how it's supposed to be done?

green oyster
#

Can anyone tell me why label at sprite resolver isnt being set to "Entry" from "Entry_1"?

#

after i set the label, i print it, and it says its "Entry"

#

but the sprite resolver still says its "Entry_1" as shown in pic?

leaden ice
#

or the label is changing at some point between the inspector being drawn and the code running

green oyster
#

it printed colour red for

#

sprite renderer, so its the right resolver, coz its the only one whos sprite render is coloured red

leaden ice
#

That's not exactly convincing

#

How about:

Debug.Log("Click here to see which resolver i'm referring to", resolver);```
#

when you click that log it will take you to the object it is referencing

green oyster
#

Tower3 so its the right gameobject

leaden ice
green oyster
#

when i click any of the prints, nothing happens probably coz im on mobile 2d unity?

#

like usually if i clicked on print, it would bring me back to code where it was printed but nope

leaden ice
#

I don't think you put the same code as I did

#

for your Debug.Log

#

especially if you're using print and not Debug.Log

green oyster
green oyster
#

yes i am, whats the difference

#

ah lol

leaden ice
#

there's a very specific reason I did it this way

green oyster
#

ah

leaden ice
#

it's so you can click on the log and it will highlight the object

green oyster
#

Ohhh, i thought print allowed same thing no?

leaden ice
#

print doesn't have the overload with the second parameter that my code is using

green oyster
#

Ohhh i see, alr i will try that

leaden ice
#

ok good

#

so then the only remaining possibility I guess is that the label is changing

#

or maybe your GetLabel() function is doing something weird

#

what does GetLabel() do exactly?

green oyster
#

its only getting "Entry" as the label

leaden ice
#

can you show more code

green oyster
#

well, gets a certain LABEL depending on the towers health, and then the label is slightly different if castle is level 1

#

but i have put a print in this code before, and its shown to print at return "Entry"

leaden ice
green oyster
#

Nope, it doesnt set it

#

the only place where i set the label is here

leaden ice
#

so then looks like the health percent is >= 0.7f and the current castle level is level1

green oyster
#

like thats the full code if u want to see

green oyster
leaden ice
#

add more logs to GetLabel()

green oyster
leaden ice
#

right

green oyster
#

if it was 1 it would print smth else

leaden ice
#

that clearly implies level is 1

#

oh right sorry

#

NOT level 1

#

yeah

#

so that's the reason

#

that's what the code tells it to do

#

I don't see what the mystery is here then

green oyster
#

Yes, it returns "Entry", which is the label that the sprite resolver should have been set to

#

but it hasn't

#

its still at "entry_1"

leaden ice
#

because you're calling a completely different function to set the label

#

GetLabel() with some parameter

#

not the same thing as resolver.GetLabel()

#

maybe you just wanted to call resolver.GetLabel()?

green oyster
#

i know that, no nope, getLabel is my custom function, to get a label depending on health

#

which returns "Entry"

#

which is good

#

the problem is that resolver label hasnt been set to that

#

and i dont know why, after i set it, i print it and it says its "Entry" but not in inspector

leaden ice
#

can you show the code for this other GetLabel() function?

#

and also what SetCategoryAndLabel does?

green oyster
#

sure, its Unitys code tho

leaden ice
#

that's a different GetLabel function

green oyster
#

Btw could it be that

leaden ice
green oyster
#

have similar named... entries

#

or not mhmm

leaden ice
#

I'm not really sure

#

tbh I'm not familiar with this SpriteResolver system

green oyster
#

so is thia bug thing

leaden ice
#

I don't really understand what it is or does

green oyster
#

within that sprite resolver

#

so is this a bug then

green oyster
#

is manually assign sprite renderer in some variable

#

and then check that sprite renderer to the one in code and see if they are same?

#

but tbh maybe theres no point in that

#

i will report this bug to unity, see if thye can fix it, coz idk

somber nacelle
waxen escarp
#

anyone here free?need help debugging

#

anyone?

vagrant blade
#

Ask an actual question and find out?

waxen escarp
#

well heres the code

#

it rotates only on horizontal, and some of the inputs are disabled

somber nacelle
#

look very closely at your VerticalRotation and HorizontalRotation methods

waxen escarp
#

ok

#

but the model keeps tumbling around even though ive applied all the rotational constraints

#

pls help

#

if anyone could send back a revised version and explain why it went wrong that would be helpful

hard viper
#

I'm thinking about Physics2D.OverlapArea(), but I need to know the most lightweight way to do this for my game. I specifially only need to know if there is AT LEAST one collider of a given layer in a region. I need to stop the computer from doing extra work if there are 200 colliders matching that description.

#

is OverlapArea the right method for this?

#

i don’t need to know what collider is there, nor an array/list of them. Just a bool

gray mural
#

but it should be ok to use it if you just want to see any collider in the area

#

you can also use OverlapBox

somber nacelle
waxen escarp
#

i did, the mouseX and MouseY were added to the wrong components

somber nacelle
#

They both did the exact same thing

waxen escarp
#

yeah

#

i actually realized that i kept a backup of the project before i started using the new input system so its all good

#

even though it would mean 2 hours of work down the drain

#

😭

#

well thank you so much

#

ill try to rewrite it a bit more meticulously

lament raft
#

it used to work just fine

#

how do i solve this

#

ah

#

it did work

#

thank you!

gray mural
#

how do I add this script to the GameObject?

public class OptionSelectButton<T> : MonoBehaviour where T : Component
green oyster
#

or drag and drop

#

the script from its place in explorer to the inspector tab

knotty sun
#

cannot add a script with generics via the inspector

gray mural
#

it just shows "OptionSelectButton"

green oyster
#

yes thats the script

gray mural
#

oh, no, it doesn't show anything

#

I have removed overload.

#

I just cannot add it

#

I have messed up with the package that should have controlled this thing after I have deleted it

gray mural
knotty sun
#

you can but you must add it via code so you can specify a T

gray mural
#

I see, not that comfortable.

#

thanks for help 😄

somber nacelle
#

Or create a concrete type that inherits from it with the type parameter specified

gray mural
#

anyway, I will have to create a few of them

#

and it will throw an error

somber nacelle
#

Well those are your options with generic MonoBehaviours

gray mural
#

I see, generic MonoBehaviour sucks.

deep oyster
#

What's the best way to create a queue of an arbitrary type?

#

It's mind boggling that List doesn't have a Pop function

#

I tried the c# Queue type but it thinks I want to fill it with objects, not my custom class I want to fill it with

edgy bough
#

Hello, I'm trying to make an Android app that measures the device speed with an accelerometer, but I have a small issue. I have successfully acquired the accelerometer data and removed the gravity, but it doesn't appear to show deceleration. It shows acceleration and I'm able to calculate speed based on that but it doesn't decelerate. My current code looks like this:

Input.gyro.enabled = true;
Vector3 accel = Input.acceleration - Input.gyro.gravity;
leaden solstice
deep oyster
#

Nevermind, turns out I just needed to explicitly cast the Dequeued thing back into my type

leaden solstice
#

For sure, but you should try to have common interface or base type you can abstract

deep oyster
#

How does Physics.OverlapSphere work? Physics.OverlapSphere(transform.position, 6.0f, 1 << wallLayerNum) is returning an empty array when I'm definitely within 6 units of a wall

deep oyster
#

2d

#

oh do I need to do overlap circle

#

or something

#

yup, there we go, Physics2D.OverlapCircle

deep oyster
#

hrrrrrm

#

So I've got an object on a 2d playing field, and I want to be able to quickly check what parts of the playing field that object can "see" without other objects in the way. Problem is, raycasting is... pretty expensive

#

Are there any fast alternatives that might work under certain circumstances

deep oyster
#

It definitely does not seem cheap when I need to do it dozens/hundreds of times per check

leaden ice
#

What problem are you trying to solve

#

Why are you doing hundreds of them

leaden ice
lean sail
deep oyster
#

I am trying to create a tree for an AI that predicts player location with a series of nodes. First I raycast to the player, if I don't hit them I can't see them. Then I need to check each of the leaves to see if the AI can see that leaf from its current location, and if it can then the player is obviously not there.

deep oyster
leaden ice
deep oyster
#

"IT" is my agent, white is my player, green is player's last "known" position

#

white is a tree of locations I predict the player could be based on its movement speed

leaden ice
#

You can either see the player or not

#

I don't understand how predicted positions relate to a line of sight check 🤔

lean sail
#

Yea sorry I dont really understand where all the raycasts come into play either

deep oyster
#

I'm not just checking if I can see the player, that's a single raycast, I'm checking if I can see each of these nodes in the white tree

leaden ice
#

Why do you care if you can see the other nodes

deep oyster
#

Because if I can see a node then I know the player is not there

#

And I should remove it from the tree

leaden ice
deep oyster
#

Why would they be, I can't see any of them, the player could be in any of those places

#

I am creating a bot that predicts a hiding player's location and tries to look for them. It cannot and must not simply know where the player is through perfect information or there is no capacity to hide from it.

leaden ice
#

I can't help but feel like this is more of a pathfinding problem than a raycasting problem somehow

deep oyster
#

Maybe you're right but I'm not sure what to do

lean sail
#

I think u are kinda creating the problem yourself.

#

You shouldnt make a node then have to filter them out, dont create the node in the first place if the ai can see it

deep oyster
#

I'm doing that, but the AI's vision changes over time

leaden ice
#

Btw you can also use RaycastCommand to do a lot of Raycasts quickly with the job system

deep oyster
#

mmm

#

I'll look into that

#

like, ok, ideally, I would have some sort of continuous heatmap, update each pixel by factoring in nearby pixel's "probability" scores, remove pixels the agent can see at any given frame and add pixels the agent can no longer see

#

but there are no continous data structures

#

and I can't easily check each pixel for "visibility"

lean sail
#

This will probably be too much to actually do if you ever have a couple of enemies

deep oyster
#

Well, right now I'm just focusing on one... It doesn't even have to be super performant I can prerecord the presentation for class I just want it to work fast enough to not crash unity...

#

and I don't actually need pixel accuracy

#

I just don't want a fixed grid because that is really bad for taking into account diagonal normalized movement

lean sail
#

What's the goal for this though? This seems a bit overly complicated to have an AI reach the player

deep oyster
#

The point is I don't want it to just go straight for the player

#

It's a game of hide and seek tag

#

if you can't hide, then what's the point

#

maybe it is overly complicated, hell it almost certainly is

#

I just want to, without knowing where the player actually is, create a prediction of where he might be and go there

lean sail
#

Well your AI does know where the player actually is, if you're raycasting to it all the time

#

I'd say it's easier to give an AI all the information then add in stupidity to it, instead of limiting information and trying to make it super smart

#

Mostly because the latter isnt cheap to calculate every, especially not every frame

deep oyster
#

I guess I'll spend some time thinking how I could do that

#

I also don't need to do this every frame

summer pivot
#

https://hastebin.com/share/kuhebikene.csharp I've been having this issue where when I kill zombie while also getting hit by the zombie, the effects still play and my health doesnt regenerate. When I looked into it, all I noticed is my isTouchingEnemy and isTouchingPlayer boolean stays set to true.

rotund knot
#

So basically, say I have two Positions/Transforms, how could I find out if a positions is in the min/max area or if it is between the two other vectors? (the areas are basically perpendicular to the path of the two positions...)

buoyant crane
#

A) Let’s figure out if it’s to the right of the min.

  • Get the vector from min to max max.position - min.position
  • Next get the vector from min to target target.position - min.position
  • Compare the Dot Product of the two vectors. If It’s greater than 0 or equal to 0 then it’s in the zone.
    B) Let’s figure out if it’s left of max
  • Get the two vectors, then dot product it to figure out if it’s in the zone
rotund knot
buoyant crane
# rotund knot Wow, thanks a lot, i'm sure i'll be able to implement it now!

Check out the gif, it’ll help you see it. End result will look a bit like

bool InZone(Vector2 target, Vector2 min, Vector2 max)
{
   Vector2 minToMax = max - min;
   Vector2 minToTarget = target - min;
   float a = Vector2.Dot(minToMax, minToTarget); // dot product
   if(a < 0) return false; // we know that the target is behind min if it’s negative 

  Vector2 maxToMin = min - max;
   Vector2 maxToTarget = target - max;
   float b = Vector2.Dot(maxToMin, maxToTarget);
   if(b < 0) return false; // target must be behind max
   return true; // true if target is in the zone
}```
rotund knot
#

yep, that's how I just finished it up, thanks a lot for the help!

scarlet kindle
#

would collider related questions apply here?

I have disabled gravity in my top-down 2d project, because I dn't plan on using it and it was causing problems with the player falling through the floor.

I got the colliders to work with the in-game objects like enemies, walls etc. However, **now that I am trying to add isTrigger = true on the Boxcollider 2D, the collisions no longer work and the player passes through the enemy. **I see the collision trigger register in the console, so I know it is working properly. Any ideas?

Suggested answer: Don't use a trigger, use the OnCollisionEnter2D event instead?
The OnCollisionenter2D method isn't being called when they collide now... so that's an issue 😦

It works when the enemies collide with each other, but not when the player collides with the enemy. No clue what the issue is. The player is moving with rb.MovePosition which should be ok I think?

#

Player rigidbody (img 1)
both enemy & player have box colliders, but the enemy doesnt have a RB

celest iron
#

Trigger does not register a collision with an incoming rigid body

#

It only serves as an event trigger

scarlet kindle
#

right so use OnCollisionEnter2D instead of that

#

but, that's not working either

celest iron
#

Is the other collider also a trigger?

leaden ice
scarlet kindle
#

no, i have disabled the isTrigger on both

leaden ice
#

kinematic bodies don't really collide with static objects

celest iron
#

Ah, yeah, that's a kinematic body lol, didn't see the screenshot

scarlet kindle
#

i tried changing to DynamicBody and had the exact same issue, except physics was applying in some way to the objects

#

collisions are working, but the OnCollisionEnter2D method is not being called

leaden ice
#

and also your code

scarlet kindle
#

box collider for Enemy

leaden ice
#

just show the full inspector for each

scarlet kindle
#

uh there's a lot of unrelated stuff in there

leaden ice
#

ok well I'm interested mainly in any collider2Ds and rigidbody2Ds

scarlet kindle
#

yes, the enemy doesn't have an RB at all.
Player has the RB I showed above, and the player's Collider looks like this

leaden ice
scarlet kindle
#

yea its not moving atm

leaden ice
#

basically to have an OnCollision2D, you need:

  • one dynamic Rigidbody2D
  • each object with a NON trigger Collider2D
scarlet kindle
#

right that was my understanding as well, which is why i'm confused that it isn't working

#

could it have to do with player movement?

leaden ice
swift falcon
scarlet kindle
#

on the enemy

swift falcon
#

then he needs a rigidbody i think

#

the caller of those events need to have rigidbody i believe

scarlet kindle
#

player movement code is

rb.MovePosition(rb.position + direction * moveSpeed * Time.fixedDeltaTime);

swift falcon
#

ur movement code is irrelevant here

#

just add rigidbody to your enemy and test it using debug.log

scarlet kindle
#

the enemy was triggering collisions if they spawned on top of each other... so

celest iron
#

Show the whole script

scarlet kindle
#

they can interact with each other

swift falcon
#

that means it was working.

leaden ice
leaden ice
#

should move via velocity

swift falcon
scarlet kindle
celest iron
#

MovePosition with dynamic body would only make it weird when colliding, but should still trigger events, no?

leaden ice
#

I mean... probably but it's weird

celest iron
#

Yeah, would be better to see the whole script

leaden ice
#

we haven't seen the code yet so there might be something wrong there

celest iron
#

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

swift falcon
#

make sure its called only on player collision with enemy

scarlet kindle
swift falcon
#

he wants to see oncollision code

leaden ice
scarlet kindle
#

thats it

swift falcon
#

u need to check for tag

#

of what object is he colliding with

#

using CompareTag() method

scarlet kindle
#

ummm

#

the method should trigger regardless?

shell scarab
#

is passing a parameter with in not passing by reference? I thought in was just ref but the function cannot reassign what that parameter is?

leaden ice
leaden ice
shell scarab
leaden ice
swift falcon
leaden ice
#

well yeah if you remove the Rigidbody2D it won't work

swift falcon
#

he doesnt want to set it back on because it will run when enemies collide

shell scarab
scarlet kindle
#

i didn't remove the RB, it's on the player

#

Adding one to the enemy does not fix it either

swift falcon
#

u need RB on the enemy if that OnCollision event is on enemy

celest iron
#

"Hi, if you do the destroy in Update() instead of OnCollisionExit() there's a chance you'll have the grounded flag true from picking up the second collider.

However, you could have cases with a racing condition causing the flag to stay false.

To go arround it, you could instead store in a list all the colliders your ball touches at any given time in OnCollisionEnter, remove them from the list in OnCollisionExit, and check in Update wether you've got at list one ground collider in list or not.

Additionnally, this method has a major flaw that on rare occasion you wont get the OnCollisionExit, it happens sometimes when there is a lag spike and you can't do anything to prevent it (as far as I know). So what you need to do is check if your player still collides with colliders in list, if your objects are axis aligned then it's a really simple and efficient bounds.contains() check.

You could also consider raycasting/spherecasting to find out if your ball is grounded."

leaden ice
swift falcon
shell scarab
scarlet kindle
swift falcon
#

sure let me see

leaden ice
#

since you are likely mutating it with a function call

shell scarab
#

yes, however i thought that was allowed when passing with in

scarlet kindle
shell scarab
#

I've done it with lists for example and i can still add things to it. But that's a reference type, so i suppose it can work different with value types

swift falcon
leaden ice
#

very different

swift falcon
#

but we dont need to use it to fix it

celest iron
leaden ice
#

in is specifically designed to prevent you from changing it

swift falcon
#

add rigidbodies and collide

#

you will see the message

scarlet kindle
swift falcon
#

do they collide?

scarlet kindle
#

yes, they've been colliding all along, that's not the issue

#

the issue is the OnCollisionEnter2D method is not calling

shell scarab
leaden ice
swift falcon
shell scarab
#

Interesting, thank you!

leaden ice
#

because the compiler can't guarantee the function won't mutate the object

#

if all you did was read a field, you would be ok

shell scarab
#

and this is only for value types, right?

leaden ice
#

yes

shell scarab
#

awesome thanks

swift falcon
scarlet kindle
#

totally had to do with player movement script

leaden ice
#

cool. Yeah MovePosition is generally intended for kinematic objects

scarlet kindle
#

ty sir (or madam)! you're a scholar, and ty @swift falcon for trying to help, I appreciate it

scarlet kindle
celest iron
#

Yes, but you would have to write your own collision detection

#

I have a script if you want to

scarlet kindle
# celest iron I have a script if you want to

im interested. I guess I need to think more on if I want to go that route or not. I mean, generally it's gonna be an oldschool RPG feel where if you run into an enemy, it triggers a new battle scene. so in that way, i'd think kinematic bodies would be a better approach. thoughts?

celest iron
#

Well, it makes the movement script way more complicated

scarlet kindle
#

I guess I could just make the enemies have a LOT of mass, right? and basically the same effect?

celest iron
#

However, it makes it more customizable

#

If you don't have many custom things you want to do, generally using dynamic bodies and just disabling gravity is simpler and works

#

I'll send you my script and the explanation.

#

May I dm you?

scarlet kindle
#

absolutely, I appreciate it

astral blaze
#

is it me or is it too confusing? anyway i was trying to make monitor fps counter and decided to put TextMeshPro on UI Screen, fps counter on UI works but the error is bothering me, its gotten become more annoying when i was trying to fix this

#

just in case its working but the error is still here

swift falcon
lean sail
swift falcon
#

MovePosition works for collisions just aswell, thats kinda trashy of you to lie just to avoid saying thanks but im not gonna interfere. you do you, just dont share misinformation intentionally

scarlet kindle
swift falcon
scarlet kindle
astral blaze
swift falcon
lean sail
#

itll be more clear then

astral blaze
lean sail
latent granite
#

Hello, is it possible to drag and drop from a custom script window to the Unity editor? I want to drag items from a UnityEngine.UIElements.ListView to a field in the inspector. My ListView is populated with VisualElements, I need to somehow get the object each dragged element is referencing outside the window and into the Editor, then entered into my desired component field on release.

astral blaze
#

here you go

#

again, still confusing tho

leaden ice
#

whatever is being used on line 33

lean sail
astral blaze
#

this one you're talking about?

leaden ice
astral blaze
#

thanks

#

i probably accidentally copied of the script without even notice

swift falcon
#

i was wondering if theres a better way to do this or some way to fix it? i added the && !m_FacingRight and Flip() to make it so that the empty attached to the player for a shooting point flipped with it but now the running animation wont play. Sorry if this isnt where this goes

leaden ice
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.

dense rock
#

I'm doing a velocity over lifetime in a rain particle system (see picture 2). Therefore I'm using the "random between two constants". When I try the following code, the first of the constants are modified (the rainVOLT.xMultiplier works), but for the rainVOLT.x (or z) Unity says "Particle Velocity curves must all be in the same mode"...
Also after applying the .xMultiplier, it's not random between 2 constants anymore (see picture 1).

rainVOLT.x = windDirection.x;
rainVOLT.xMultiplier = windDirection.x + 10;
rainVOLT.z = windDirection.y;
rainVOLT.zMultiplier = windDirection.y + 10;
swift falcon
#

and do your other animations work when flipped?

leaden ice
#

We don't know what rainVOLT is

dense rock
#

thats the velocity over lifetime module

#
rainVOLT = rainParticles.velocityOverLifetime;
leaden ice
#

show more code please

#

not one line at a time

dense rock
#

just a vector 2, it isn't necessary for the problem i think

swift falcon
#

it is

leaden ice
#

definitely necessary

swift falcon
#

key part lol

dense rock
#

thats gonna take some time, give me a sec

leaden ice
#

by doing this:
rainVOLT.x = windDirection.x; that assignment is going to set the MionMaxCurve to "single constant" mode

dense rock
leaden ice
#

you would need to do something like:

MinMaxCurve xCurve = rainVOLT.x;
xCurve.curveMin = something;
xCurve.curveMax = something;
rainVOLT.x = xCurve;```
swift falcon
#

my bad oleex didnt notice u set it to y

dense rock
#

no worries but thanks ill try that ^^

dense rock
swift falcon
leaden ice
#

assuming it was already in that mode

#

Since we didn't modify the mode

dense rock
#

is it random for each particle, or the same random value for each one?

leaden ice
#

random for each I assume, but this code is not changing what it was before

dense rock
#

ohh i c