#archived-code-general

1 messages · Page 450 of 1

fiery steeple
jagged belfry
#

I'm trying to instantiate an arrow by code in the bow of my character, when I press the shoot button and I'm using addforce but I don't know why sometimes when I shoot the arrow it goes out of the map downwards and other times it falls to the ground without any problem, I don't know what would be the best way to shoot the arrow, the arrow is a prefab and has a rigidbody and a box collider, the arrow prefab shouldn't be the problem

Later I can send a screenshot of my code

leaden ice
#

Use Debug.Log in OnCollisionEnter to find out

#

also don't share code as screenshots

#

!code

tawny elkBOT
hoary yoke
#

Hey guysss my sprite (the highlighted spaceship) won't load.... why?

leaden ice
#

See this cute little horizontal white line above the hand icon

#

that's the top of your actual game camera viewport

#

your spaceship, since it's a SpriteRenderer, needs to be inside that rectangle to be visible in game view

#

(it's also HUGE right now)

#

You're getting confused by how Unity displays the overlay UI in scene view, that's all

hoary yoke
#

ohhh okay thankss i get it

leaden ice
#

your other option is to use a UI Image instead of a SpriteRenderer

#

and make this thing part of the UI

hoary yoke
#

yess i will

#

thank you sm

pine ivy
leaden ice
pine ivy
#

the pauseMenu script cant locate the instantiated menu

leaden ice
#

Also why is it looking for some other object

#

when it is ITSELF the pause menu object?

#

I would recommend reading this, you seem to be confused about how singletons should work and your implementation is weird/overcomplicated and not really correct: https://unity.huh.how/references/singletons

jagged belfry
pine ivy
#

so i got the menu to instantiate properly, but its outside of the canvas parent, so how can i add it in upon instantiation?

leaden ice
#

Instantiate has a parameter for a parent object

pine ivy
#

ah thanks

sleek tangle
#

Hey, i'm trying to detect my mouse over UI elements, i have one on each side of the screen, and it seems like it detects the one on the left side but not the one on the right side? They're completely identical and this is really throwing me off

#

I'm using IPointerEnter and Exit handlers

sleek tangle
#

Nevermind, I switched to graphic raycasting and it works now

leaden ice
#

switched to it - from what?

jagged belfry
#
//script arrow 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ArqueroAttack : MonoBehaviour
{

    public int daño = 10;
    public float tiempoVida = 10f;
    // Start is called before the first frame update
    void Start()
    {

        Destroy(gameObject, tiempoVida);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("enemy")) 
        {
            other.GetComponent<EnemigoMelee>().TakeDamage(daño);
            Debug.Log("¡Flecha impactó al enemigo!");
            Destroy(gameObject); 
        }
            else if (other.CompareTag("Suelo"))
        {
            /*Rigidbody rb = GetComponent<Rigidbody>();
            //rb.velocity = Vector3.zero; 
            //rb.angularVelocity = Vector3.zero;
            rb.isKinematic = true; 
            transform.SetParent(other.transform);*/
        }
        /*else 
        {
            Destroy(gameObject);
        }*/
    }
}
//script player:
public void DispararFlecha(){
            GameObject nuevaFlecha = Instantiate(flechaPrefab, puntoDisparo.position, puntoDisparo.rotation);

            Rigidbody rb = nuevaFlecha.GetComponent<Rigidbody>();
            if (rb != null){
                rb.AddForce(puntoDisparo.forward * velocidadFlecha, ForceMode.Impulse);
            }
        }

I don't know why when I shoot it does strange things, the arrow goes down through the ground of the map and it doesn't shoot well, I have an arrow with a rigidbody with gravity activated and a collider with the trigger activated, and I also use an empty game object located in the bow to be able to specify the shooting point (puntpDisparo)

leaden ice
#

And your code in OnTriggerEnter ignores everything that doesn't have the enemy tag

lucid brook
#

Hey, I'm making a VR game with a wall run mechanic where after a player starts wall running they get a full 360 degree control over where they go along the wall. So they can go up, down, left, right and anything in between. With the forward direction always being where they are looking.

Where I'm running into problems is with getting the movement direction while the player is on the wall.
Because it's a VR game I can't rotate the camera or the player object around to get the player's forward direction, at least not without unparenting the controllers. Instead I have an empty gameObject called directionIndex that I rotate to match the camera's Y rotation and use that to base the movement direction off while the player is on the ground.

directionIndex.eulerAngles = new Vector3(0f, head.eulerAngles.y, 0f);

Vector3 targetVelocity = new Vector3(moveInputValue.x, 0, moveInputValue.y) * (moveSpeed * moveSpeedMultiplier);
targetVelocity = directionIndex.TransformDirection(targetVelocity);

So what I would ideally need is to replace the first line of the code above with one that applies the player's head rotation along the walls normal to the directionIndex object (in world space). Does anyone have examples of that type of code?

(I've tried asking this a couple of times but my extremely limited knowledge of rotations and quaternions has always hindered my explanation of the issue and has stopped me from understanding and implementing the answers I got. This time around I took extra time to make sure I write everything down as best as I could. Thank you for reading this.)

steady bobcat
#

i remember this yes. i presume you dont mean 360 control

#

seeing as a wall is a 2d plane so i presume 360 degrees on 1 axis is what is desired

steady bobcat
#

I tried to help before by explaining how you rotate the XZ plane movement rotation. doing Quaternion * Quaternion will rotate the first by the second.

#

Try:
directionIndex.rotation = Quaternion.Euler(0f, head.eulerAngles.y, 0f) * Quaternion.LookRotation(Vector3.forward, wallNormal.normalized);

lucid brook
steady bobcat
#

you can try just rotating the movement vector instead with Quaternion.LookRotation(Vector3.forward, wallNormal) * moveInputValue

#

you can do Quaternion * Vector3 to rotate a vector (around 0,0,0)

#

The point is to change their input from XZ to the wall "plane" right?

lucid brook
steady bobcat
#

Aha this may be the rotation you need actually Quaternion.FromToRotation(Vector3.up, wallNormal)

lucid brook
steady bobcat
#

Try this:

Vector3 targetVelocity = new Vector3(moveInputValue.x, 0, moveInputValue.y) * (moveSpeed * moveSpeedMultiplier);
targetVelocity = Quaternion.FromToRotation(Vector3.up, wallNormal.normalized) * targetVelocity;
lucid brook
#

together with
directionIndex.rotation = Quaternion.Euler(0f, head.eulerAngles.y, 0f) * Quaternion.LookRotation(Vector3.forward, wallNormal.normalized);?

steady bobcat
#

Ah I guess the input needs to be rotated by the player camera dir first?

#

@lucid brook If so here is a new version where we rotate input by the player cam Y rotation only first, THEN the wall normal rotation:

Vector3 targetVelocity = new Vector3(moveInputValue.x, 0, moveInputValue.y) * (moveSpeed * moveSpeedMultiplier);
targetVelocity = Quaternion.Euler(0f, head.eulerAngles.y, 0f) * targetVelocity;
targetVelocity = Quaternion.FromToRotation(Vector3.up, wallNormal.normalized) * targetVelocity;
#

instead of using a transform to rotate a vector we do it ourselves so directionIndex is not needed

lucid brook
#

I don't think that is going to work because it's still using the Quaternion.Euler(0f, head.eulerAngles.y, 0f). when I am on the wall I don't need the Y

steady bobcat
#

I don't know what moveInputValue is from but if you want movement to be relative to the player look dir then it is needed.

lucid brook
#

and the reason I can't just have the players distance from the wall be a set value is because I have them riding on a sort of spring.

steady bobcat
#

thats a different issue and is easier to solve

primal gale
#

Im trying to implement knockback in my 2d platformer and im just trying to work it out on paper first.

Just a little confused on how exactly I need to calculate the knockback direction

maybe taking the bullet transform that is being fired, compare it to the enemy rigidbody, and apply the opposite of that bullet transform onto the enemy rigidbody?

lucid brook
#

Do you want the player to be knocked back in the direction of where the bullet came from? like the bullet comes directly from the right so the knockback sends to you the left?

lucid brook
primal gale
steady bobcat
# lucid brook it is?

a simple way would be to "release them" from the wall movement if their look dir angle (compared to the wall normal) goes above some value (actually probably below an angle)

primal gale
#

like if I hit the enemy from the bottom it would just be sent upwards depending on angles and whatnot

lucid brook
steady bobcat
#

then i dont know what you want anymore 😆

lucid brook
primal gale
steady bobcat
#

ive already given some info on how you should rotate a 2d movement vector for some surface normal. im not sure whatelse to say

lucid brook
#

Something like that should work I think

#

rigidBody.linearVelocity = Vector2.zero; sets your speed to 0 so your knockback will always be the same

hollow swan
#

Hey mate sorry to ping i know it's been a while but i can't for the life of me figure out how to make this work, i'm trying to do if my bool is true from my main class then it show an ui but i can't get the class since getcomponent can't be used and i can't us ()target; so i'm gonna stick to the hold editor way and just make an array for multiple variable instead of one big one ;w;

primal gale
lucid brook
#

woops sorry, I wrote that in my current project. that should be your bullet

#

you could also do rigidBody.linearVelocity = rigidBody.linearVelocity / 2; if you don't want your played to lose all their speed

primal gale
#

one more thing, lets say I had this on my enemy script, how would I call an instantiated bullet?

lucid brook
#

where would you put the knockback code? on the bullet or on the enemy?

primal gale
#

well if I wanted it on my bullet wouldnt I need to get the rigidbody of the enemy I hit?

#

or if it was on my enemy I would need to grab the bullets my player is instantiating

steady bobcat
#

Im gonna point out that your original idea of "bullet to enemy dir opposite force" is correct

#

its really not that complex

#

You do target.position - me.position to get a direction from me to target. It should be normalized before use with forces.

primal gale
#

my brain isnt working my bad unity is still rather new to me, would I call the target using an OnTriggerEnter2D method?

steady bobcat
#

well i presume you already use OnCollsisionEnter2D or trigger version for damage so you can do it there too

#

slightly different ofc depending on if its done on the bullet or enemy

primal gale
#

yeah I just realized I already have like half of this

steady bobcat
#

just try it and see, not hard. just use AddForce() with Impulse mode

primal gale
#

aight bet thanks guys

shell scarab
#

Isn't this suppose to work? Why is my unity not referencing this dll?

[CustomPropertyDrawer(typeof(NormalizedAttribute))]
    public class NormalizedAttributePropertyDrawer : PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            dynamic obj = property.boxedValue;

            switch (obj)
            {
                case Vector2:
                case Vector3:
                case Vector4:
                    obj = obj.normalized; // error on this line
                    break;
                default:
                    break;
            }
        }
    }

error: One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

#

im almost positive I've done something like this before

primal gale
#

ok nothing at all happened

#

oh wait Im not applying any froce

#

yooo I got it to work

#

that really was much easier than all the knockback videos made it

#

that was like 2 lines of code

violet nymph
#

Usually is a lot easier than videos make it seem

simple egret
shell scarab
simple egret
#

Error means it doesn't

shell scarab
#

has it never supported it? As I said I could have sworn I've done similar things before.

leaden ice
#

I think Unity supports dynamic at runtime but only if you're using the Mono scripting backend (not IL2CPP). But I also thought the editor always ran Mono so I'm surprised it's not working TBH

ocean hollow
#

theoretically speaking, how bad is it to thread the same value via an overload across different functions?

shell scarab
ocean hollow
#

would this be considered bad practice or is it not that bad?

jagged belfry
shell scarab
#

If you're only calling other functions in the same class like that in each step, bad.

Otherwise, it's not necessarily 'bad' but it might be argued that something like this is more readable

void DoSomething() 
{
    int importantValue = 42;
    var v = StepA(importantValue);
    v = StepB(v);
    v = StepC(v);
}

int StepA(int value) 
{
   //something
   return processedValue;
}

int StepB(int value) 
{
    //something
     return processedValue;
}

int StepC(int value) 
{
    // final use or maybe even continue
     return processedValue;
}
shell scarab
#

doing it this way likely adheres more closely to the single responsibility principle as well

ocean hollow
short flame
#

is there a way to save a list of objects to json? i'm using JsonUtility.ToJson which seems to work pretty well for most things, but when it comes to this list it saves them as instances

steady bobcat
short flame
fiery steeple
#

This works, thank you so much 🙏

steady bobcat
short flame
#

looks like this

#

the list is List<Catchable>

steady bobcat
#

you will need a class to hold the list and then serialize that class instance.
Some things like Texture and AnimationCurve wont work ofc

#

this is why its better to do things a custom way with unique ids and prefabs you manage so you dont have to fuck with this

short flame
#

i'm very new to the whole "save file" schtick

steady bobcat
#

You can invent your own to suit your needs.
E.g. ScriptableObject with a unique string id + prefab. When saving you save this Id + extra data. Later you find the scriptable object with the id and instantiate the prefab, then load back the extra data (e.g. ammo, health).

#

You probably want to avoid trying to json serialize a mono as it will cause issues (and if you use another serializer like newtonsoft json it will require many extra things to work somewhat correctly).

lucid brook
#

I think I have figured out an abstracter way of asking a question I have asked before.

So I am getting the blue walls normal, represented by the darker blue cylinder.
I want to get the rotation of the toaster along that axis.
So that when I take that rotation and apply to it a another toaster it will only rotate along the blue cylinder/that green plane
(Don't ask why I have 2 toaster, that's none of your business Giggle)

lean sail
lucid brook
#

yeah but I need to rotation to be based off of the first toaster.

#

kinda like toaster2.eulerAngles = new Vector3(0f, toaster1.eulerAngles.y, 0f); but on any plane, not just on the Y

lean sail
lean sail
lucid brook
#

give me a sec, I think I know a way to visualize it better

lean sail
#

I do find it confusing what you want, maybe take a look at the quaternion docs and see if any methods stand out? Maybe something like to angle axis here

steady bobcat
#

Quaternion.FromToRotation(Vector3.up, wallNormal.normalized)

#

the solution is still using this to make a global y euler rotation be on this "plane"

#

As explained earlier, you can multiply quaternions together to rotate one by the other.

grave bloom
#

does anyone know why profiler cpu usage does not display any highlighted blue for this collision manager ? from the ss i can tell the collision manager is taking 11ms and it falls under the script cpu usage for sure (since it is in update event)

steady bobcat
#

maybe cus you de selected "Physics" ?

grave bloom
#

i tried turn on all usage category, still no luck

ocean hollow
#

is there a reason why my IDE is suggesting this over my current solution? Is this better somehow?

cosmic rain
# grave bloom

What exactly is the cause of the 11ms. If it's something like GC, that might not be mapped properly.

cosmic rain
eager tundra
#

it does, it's pretty neat

#

a lot less typing

#

it doesn't fully support all the possible types of pattern matching, but in this case it's fully supported

cosmic rain
ocean hollow
#

im sure that syntax sugar would go very well on top of my spaghetti code

signal bane
#

hello 👋 is there a way to disable OS trackpad gestures for games while you're playing?

mellow sigil
#

Which OS? Although I think it's out of your control in all of them

somber nacelle
#

or at the very least requires native plugins

keen gust
#

Hello, I have some additive scenes. Is there a way for a camera to record only what's inside his own scene without using layers ?

somber nacelle
#

without using layers
unlikely, the layers used for the camera's culling mask is what determines what it can and cannot see

keen gust
#

Arf, ok thanks

round violet
#

so im using the mobile URP template, and each time i undo something i get this error

SerializedObject target has been destroyed.
UnityEditor.SerializedObject:UpdateIfRequiredOrScript ()
Unity.Notifications.NotificationSettingsProvider:<Initialize>b__19_0 () (at ./Library/PackageCache/com.unity.mobile.notifications@439e41e635a0/Editor/NotificationSettingsProvider.cs:79)

i didnt use the notification settings provider yet, so i wonder how a default unity template project errors like this

vestal arch
#

the list destructuring thing?

eager tundra
#

not sure which exact features are supported

trim schooner
#

Unity lags behind, it isn't on the latest C#

night harness
#
        (float,string) displayText = remainingTime switch
        {
            float i when i > 4f => (80, "First to 5 points wins"),
            float i when i <= 4f && i > 3f => (300, "3"),
            float i when i <= 3f && i > 2f => (300, "2"),
            float i when i <= 2f && i > 1f => (300, "1"),
            float i when i <= 1f && i > 0f => (300, "GO!"),
            _ => (0f, string.Empty)
        };

i was suprised when i found out you can do conditionals in the matching too 😄

vestal arch
#

also you don't really need the separate 3/2/1 cases

thick terrace
#

that isn't really pattern matching (except float i which isn't much of a pattern 😄 ), it's a switch expression with a condition on each branch! pattern matching would look like this (notice no variable names and and instead of &&):

        (float, string) displayText = remainingTime switch
        {
            > 4f => (80, "First to 5 points wins"),
            <= 4f and > 3f => (300, "3"),
            <= 3f and > 2f => (300, "2"),
            <= 2f and > 1f => (300, "1"),
            <= 1f and > 0f => (300, "GO!"),
            _ => (0f, string.Empty)
        };
round violet
#

are ECS managed singleton supported ?

#

all functions i find to get my singleton requires T to be unmanaged

round violet
#

i am having a hard time understanding how components should be done when of managed types, a lot of functions (such as queries) dont accept them

signal bane
#

Thanks though, I thought the same thing 😦

maiden schooner
#

Not sure if it belongs in this channel in particular, but I'll ask anyway.

I've been trying so hard to find a way to have it so that my player can slide against slopes without a slowdown, but I just can't seem to find a solution regarding that anywhere, at least in terms of a top-down RPG game.

I'm currently using Unity2D and the linear velocity of my RigidBody to move my character. My game is mainly top-down, and not a platformer.

Here's a visual representation of what I'm talking about:

steady bobcat
#

otherwise perhaps you need to use ray casts/collision events to detect movement into a wall and instead change input to be parallel to avoid wall friction?

maiden schooner
#

Yeah, I did the physics materials already, and it works when I simply want to slide against a wall, but I still slow down when sliding against slopes.

#

I wasn't sure how to go about using ray casts because I'm using a Box Collider 2D

steady bobcat
maiden schooner
#

It's kinda weird, because I even checked the velocity when this happens and the speed is reduced regardless

steady bobcat
#

got a video showing the colliders?

maiden schooner
#

Yeah, here, let me get it set up real quick

eager tundra
maiden schooner
cedar sand
steady bobcat
cedar sand
steady bobcat
cedar sand
#

can i use a git url in scoped registry?

steady bobcat
#

the point of this is to tell unity "hey, a package that starts with com.mycoolcompany probably exists on this host
git url just cannot do this so you cant make it work

#

open upm exists to help with this, most of them are sourced from github repositories

covert zenith
#

can someone help me, I'm making a battle system that has a shield that can face up down left or right and it's giving me weird angles except for up my code:else if (soulstate == 3)
{
myrb.gravityScale = 0;
transform.rotation = Quaternion.identity;
transform.localPosition = new Vector3(0, 0, 0);
shield.gameObject.SetActive(true);
if (Input.GetKeyDown(KeyCode.UpArrow))
{
shield.localRotation = quaternion.identity;
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
shield.localRotation = quaternion.Euler(0, 0, 90);
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
shield.localRotation = quaternion.Euler(0, 0, 180);
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
shield.localRotation = quaternion.Euler(0, 0, 270);
}
}

somber nacelle
#

why are you using Unity.Mathematics.quaternion instead of UnityEngine.Quaternion? that is the issue, quaternion.Euler expects radians not degrees while Quaternion.Euler is what you want because it uses degrees

#

also !code

tawny elkBOT
covert zenith
#

thx

shadow wagon
#

It often automatically uses the System MathF which is always annoying when I dont spot it right away and realise seconds later when I dont have access to everything.
Same goes for Random

steady bobcat
maiden schooner
#

Hm... I prefer my movement unnormalized just for the sake of the game I'm making

somber nacelle
shadow wagon
#

Thats true, definitely in the case of MathF vs Mathf. But Random could be System.Random or UnityEngine.Random theres no way to distinguish

#

only when you hover over it to see which one its using

steady bobcat
maiden schooner
#

Huh, alrighty then, I guess I'll see what I can do then

somber nacelle
#

if you want to support analog input for movement then just clamp the magnitude to 1 so it cannot go beyond it but can still be lower than 1 to allow slower movement

#

if you don't need that slower movement or don't care about analog input then you can just normalize it because it makes no difference then

maiden schooner
#

Are you talking to me?

naive swallow
#

Trying to use a small 64x64 pixel image as a "brush" for editing terrain at runtime, and I've got it making a blocky shape by just naievely sampling the closest pixel to the area of the terrain I'm editing (Picture below, it's a gradient circle image so it's scaled it up to 1000x1000)

If I want to smooth this, how might I go about sampling the image in a way that smooths it out? This seems like something most image programs do when blowing up a pixelated image but I need to do it mathematically when setting up the matrix.

The code that does that naive sampling:

int imageXCoord = Mathf.RoundToInt(Mathf.Lerp(0, brushSprite.width, Mathf.InverseLerp(0, width, x)));
int imageYCoord = Mathf.RoundToInt(Mathf.Lerp(0, brushSprite.height, Mathf.InverseLerp(0, height, y)));
BrushMatrix[x, y] = brushSprite.GetPixel(imageXCoord, imageYCoord).r;

this is the body of a loop over a portion of the terrain defined by width and height, in this image, they're both 1000. The image is a 64x64 grayscale mask.

naive swallow
#

Flawless, no notes. Thanks!

naive swallow
#

Okay, more terrain math: Trying to go from a world space Vector3 to a terrain XY Index that I'd pass as the start location for terrainData.GetHeights.

I can't find any data about what those indices even are, other than 0,0 seems to be the bottom-right corner through basically just plugging and checking. How would I find out what the "Terrain space" coordinates of a world location would be, taking into account the terrain's transform position and size?

#

Since the 0,0 corner seems to be the transform.position of the terrain, I could do some InverseLerp/Lerp remapping, but what are the sizes of that heights array? Are they in world units, or something else? Is it just terrainData.size.x and terrainData.size.z? Those are floats, but the indices are ints so I don't know what to do to rectify that, they don't seem to be the same dimension

cold parrot
#

There might be an off-by-1 somewhere

steady bobcat
#

should be floored to int

sleek bough
#

This is a code channel

pure ore
#

I love coding

using InControl;
using UnityEngine;

namespace J3G.Input
{
    using Input = UnityEngine.Input;

    public class PlayerInput
    {
        // Player Input
        public static float MoveX() => GetInput(GamepadUtils.GetAxis(InputControlType.LeftStickX), UnityEngine.Input.GetAxis("Horizontal"));
        public static float MoveY() => GetInput(GamepadUtils.GetAxis(InputControlType.LeftStickY), UnityEngine.Input.GetAxis("Vertical"));
        public static float MoveXRaw() => GetInput(GamepadUtils.GetAxisRaw(InputControlType.LeftStickX), UnityEngine.Input.GetAxisRaw("Horizontal"));
        public static float MoveYRaw() => GetInput(GamepadUtils.GetAxisRaw(InputControlType.LeftStickY), UnityEngine.Input.GetAxisRaw("Vertical"));
        
        // UI
        public static float StickYAxis() => GamepadUtils.GetAxis( InputControlType.LeftStickY );
        public static float DPadYAxis() => GamepadUtils.GetAxis( InputControlType.DPadY );
        public static bool Submit() => GetInput( GamepadUtils.GetButtonDown( InputControlType.Action3 ), UnityEngine.Input.GetKeyDown( KeyCode.Return ) );
        public static bool Back() => GetInput( GamepadUtils.GetButtonDown( InputControlType.Action2 ), UnityEngine.Input.GetKeyDown( KeyCode.Escape ) );
        
        private static T GetInput<T>(T inputGamepad, T inputKeyboard)
        {
            T obj = default(T);
            if (!inputGamepad.Equals(default(T)))
                obj = inputGamepad;
            if (!inputKeyboard.Equals(default(T)))
                obj = inputKeyboard;
            return obj;
        }
    }
}
olive crypt
#

Hi guys, I'm having a bit of a weird issue when parenting my player controller

I've got a box collider 2d set up on my moving platform, so that upon entering, my player controller's parent is set to the moving platform
though the movement with the platform seems fine, every time I enter or exit the collider there is a small but very noticeable jitter

Is there any way to fix or avoid the jitter?

dusk apex
olive crypt
#

Of course, give me 2secs

leaden ice
#

Also !code please

tawny elkBOT
olive crypt
#

player is a Rigidbody2D controller, with the movement using rb.AddForce() applied in FixedUpdate
platform is stationary during this issue, as I can send a video of in a second, so I'm not sure that it is causing the issues

#

framerate is quite poor even though it was fine before i trimmed it

#

the box collider 2d surrounds the platform (space looking thing on the right)

dusk apex
#

Show how you're moving through code (checking for other complications)

olive crypt
#

yea sure thing
might be a little more complex to understand

#
public void Move(Vector2 moveDelta)
{
    if (!movementEnabled) return;

    isGrounded = Physics2D.OverlapCircle(groundCheckPoint.position, settings.GroundCheckRadius, settings.GroundMask);

    rigidBody2D.drag = isGrounded ? settings.GroundDrag : settings.AirDrag;

    Vector2 move = new(moveDelta.x * settings.WalkSpeed, 0f);
    rigidBody2D.AddForce(move);
}
#

this is being run inside of fixedupdate by my player class

#

the movement function is contained within a subclass

#

no issues with the player controller or platform jittering whatsoever, its only the act of parenting one to the other (player to platform) that causes it
i'm going to try create an empty and parent to that instead just to make sure

#

closer look, hopefully the framerate shows it more obviously this time
I've tried both with a new empty gameobject with the parentable zone component
also with just a 'parentablezone' tag that can be checked against (this version is in the video, same behaviour either way)

dusk apex
#

Are you referring to camera jitter, player jitter or something other?

leaden ice
lean sail
#

parenting a rigidbody isnt a good idea

leaden ice
#

RIgidbodies basically ignore that stuff

#

and follow the physics

olive crypt
#

ahh
had a feeling there might be some issues with physics
are there any alternatives?

thing is, in this case it doesn't matter because the lift will be going vertically, and the collider on it will just force the player up when it needs
but for horizontal movement, the platform will just slide out from underneath the player

leaden ice
olive crypt
#

ah sweet, that looks promising, thank you!

royal lava
#

My VSCode (or maybe Unity) keeps creating bin and obj folders in multiple places in my assets hierarchy. I can't find a way to prevent that on Google, so my Unity project doesn't compile until I delete them. It happens every minute. Does anybody know what's wrong?

lucid brook
#

Alright, I have a new way of solving a problem I am having, but I am going to need some help with the math cause I am not that smart patrickdumb

I have a vector3 force and a collider's normal, and I need to not apply any force on said normal. So if the force is (1.3, 2.4, 0.9) and the normal is (0, 1, 0) I need the new force to become (1.3, 0, 0.9).
So it's like I need to invert the normal; 0 becomes 1, 0.2 becomes 0.8. Because then I could just multiply the force by that inverted normal. But like I said, I'm going to need some help with that.

primal gale
#

I want to make a flying 2d enemy and im aware that using a Kinematic rigibody2d can let you keep an enemy in the air.

I also have knockback which works off of physics, so how can I keep the knockback on my enemy while its floating?

lucid brook
steady bobcat
primal gale
#

oh wait theres literally a gravity scale mb

#

oh but now it just continously takes knockback

#

I guess ill make a coroutine for it getting hit to turn off gravity scale

steady bobcat
#

drag

#

drag exists so velocity decays over time, emulating air resistance

lucid brook
#

ive been stuck on this for weeks.

leaden ice
primal gale
steady bobcat
# lucid brook at least i'm trying shit

Im gonna make a small example to illustrate something.
Thinking about how we can translate from one "space" to another is important (e.g. world to another transform local space)

primal gale
#

also really quick, is Time.deltaTime the same as Time.time?

leaden ice
#

have you read the descriptions?

primal gale
#

quite possibly not

leaden ice
#

You should read them

primal gale
#

okay so deltatime uses the last frame -> current frame while time uses the current one?

leaden ice
#

Time.time is how much time since the game started running
Time.deltaTime is how much time since the previous frame

primal gale
#

oh okay

leaden ice
primal gale
#

so time.time would be used for things based on how long the game has been running, while deltatime could be used for an action based timer?

leaden ice
#

sure - they both have a myriad of uses

lucid brook
lucid brook
steady bobcat
#

@lucid brook I see you got a solution. I made a quick demo that demonstrates doing movement and rotation relative to a surface based on its normal. Would this be useful for you to look at?

#

I wanted to make sure my thinking was right too so i dont mind either way 🙂

lucid brook
#

can I see the code for that?

steady bobcat
#

I did a script for movement and one for rotation. Both use a raycast and the resulting hit normal to "adjust" to the surface

#

both prefabs use the same scripts

lucid brook
#

I don't think that would have worked. cause I need the rotation to be based off of the camera. I need the directionIndex objects rotation to still be based off of the cameras.

steady bobcat
#

The aim of this is to show you how you adjust things using rotations instead of relying on jank transform stuff

#

the move input is the same for both but they do different things and arent children of the planes:

#

We can still use a transform to do things such as rotate a vector. Hell you can even just take the forward vector of the camera and then rotate it as I did

#

*corrected, i meant vector

#

I know this stuff can be confusing, I just wanted to demo some way of doing something like this (changing a movement vector to move relative to a slanted surface instead of a flat surface)

lucid brook
#

idk that might have worked but I am not nearly smart enough when it comes to code to understand/implement that.

steady bobcat
#

You will learn with time and trying things. I know that we can rotate a vector using a quaternion. I know the movement vector I have is intended for movement on XZ, where up is Y1. Therefore we can get a rotation to go from our normal up to the "surface up(the normal)" and rotate our input so its now relative to this surface up instead.

lucid brook
steady bobcat
lucid brook
#

I've accepted that I will never fully understand that stuff. I have been trying to get it on and off for 5 years or so. and I still got nothing.

#

my brain is just not build for it

#

I'll focus on game design and be happy

latent latch
#

there's a bit more to it too, you need camera relativity on the direction if this is 3rd person

#

which I assume this is supposed to be spiderman according to the avatar haha

lucid brook
#

it's in vr so that's not an issue.

#

but the issue is solved. rob is just trying explain something

steady bobcat
#

😆 hopefully something got through

lucid brook
latent latch
#

oh yeah first person should be easy enough

lucid brook
#

well apparently not. it's fixed in a different way though.

rare thorn
#

Hey everyone! I've run into an issue i'm really struggling with fixing

I want to parse a Monobehaviour script as Parameter to another script, as can be seen in the picture. Ideally i would like to be able to just drag-n-drop my scripts here. However, this doesn't seem to be a possiblity, and it can only happen if set the parameter type to Monoscript, but then i cannot build my project. I know switching to Scriptable Object would be the optimal solution, but the attacks depend on Coroutines, so i'm worried i will have to start over if i do that.

Please help! Cheers! :)

#

For context: The reason i want to do this, is i want to add components for each script that would appear here.

leaden ice
#

you would drag an object with that script attached.

#

also - regarding coroutines - you would probably want to just run the coroutine on some central coroutine runner anyway, not on the individual behaviors here

rare thorn
#

So i would have to create empty gameobjects, with 1 script attached, then use that as parameter?. AKA there is no easy way to simply input a script?

leaden ice
#

it's just a text file

#

the class you define in that script is a blueprint for a component

#

Components in Unity do not and cannot exist except as things that are attached to GameObjects

#

You could do this in other ways

#

but not in the way you have designed here.

rare thorn
#

Wamp wamp, thanks for the answer though! :)

#

I didn't realize Monoscript was editor-exclusive, so i designed myself into a hole 😢

long bison
#

Idk where to ask about this, but I'm trying to change the "front" direction of a prefab. I'm using LookRotation() to have it point towards objects, but the "front" of the fork is not what I want it to be. How could I change the "front" of a prefab?

naive swallow
long bison
#

how do I know which direction of the empty is forward?

vagrant blade
#

The blue axis

long bison
#

thx

thick terrace
lyric veldt
#

hey guys does anyone the best way to implment a highlight object script, heres my current hover code, it works but it makes the game very lagging if you keep hover and unhover the object. The highlight material is a thin white outline so I cant just override the origonal material

latent latch
#

Well, few things but first are you applying these materials every frame or only on apply and deselect?

#

I suggest doing a toggle, but the overall problem here is you're creating a new material each time which is usually a big no-no for reusable stuff. Ideally make a material beforehand and cache it somewhere, then swap out the material when you need to use it.

lyric veldt
#

if thats what you mean

latent latch
#

If you have say a bunch of units you can highlight, I also suggest using a single shared material

latent latch
#

but that's less of a problem if you do a cache/shared material anyway

lyric veldt
#

like it doesnt swap every frame

#

if thats what you mean

#

here let me record a vid

leaden ice
#
  1. you could keep reusing the same array instead of making a new one each time
  2. what's calling OnHoverXXX methods?
latent latch
#

In that case yeah just make a one-time material. What's happening maybe is the materials arent being garbage collected perhaps cause you're newing them

lyric veldt
latent latch
#

Usually if you do want to create a bunch of new material instances you want to manually destroy them if possible

leaden ice
# lyric veldt

my gues is the lag is coming more from Unity drawing the inspector than anything else, TBH

leaden ice
#

not .materials

lyric veldt
#

doesnt shared material like

#

changes material globally

leaden ice
#

It only matters if you're actually modifying the materials

lyric veldt
#

for all the object using it

leaden ice
#

if you're just changing which materials you're using

#

it's fine

#

make sense?

lyric veldt
#

ye

#

let me try it out

latent latch
#

I'd make a single shared material for highlighting which can be applied to multiple units without having to modify it

leaden ice
#

the thing is this material is implemented as a second material

#

so you do need to modify the array

#

but it seems like the material itself isn't being modified

latent latch
#

Ah, it's a submesh outline

lyric veldt
#

oh yeah right

leaden ice
#

well if material count > submesh count it will just render the same submesh again, with the second material

lyric veldt
#

add a boolean parameter

#

inside the

#

shader graph

#

and just toggle it on and off when im hovering over the object

leaden ice
#

Well it would be a float alpha param more like.

But this has a cost

#

it means you';re going to be double rendering all your objects all the time

#

it's better not to do this

lyric veldt
#

but there isnt that many highlightable obj so it should be fine

#

probably a really stupid way to implement this effect lol

#

im hella stupid 😭

latent latch
#

It's pretty common

#

Otherwise you have to integrate it into the shader, or do something like post-processing outlining

#

Really more of an issue on skinmesh renderers

lyric veldt
lyric veldt
#

lol

toxic lichen
#

Why is there a slight difference between how the above text (rendered to a Render Texture and displayed in a Raw image) and below text (in an overlay canvas) looks?

#

Does it have to do with the RT settings?

#

Or maybe the TMP shader?

twilit fox
#

Hello everyone, does anyone know how to achieve this behavior?

I want to have a black image overlay covering the screen, including UI buttons, and then use a second image to cut out a portion of that overlay—so the user can click the button underneath it. This is useful for creating tutorials.

Currently, I achieve this by duplicating multiple background images. I’ve also tried using shaders (one for the black overlay and another for the cutout), but I haven’t been able to get it working properly.

Does anyone know how to do this or if there’s a better approach for tutorial systems?

twilit fox
#

Tried it but can't seem to make it work.

leaden ice
#

unless I misunderstand

twilit fox
#

I don't think this is the correct approach, since the cutout image needs to both disable raycast targeting in that area and visually cut it out.

leaden ice
#

I think you could just handle the raycast targeting stuff separately

#

either with canvas groups or just looping through all your other ui elements to modify the raycast target thing as needed

twilit fox
#

Yeah, that could work, but I remember there's an approach that uses two shaders—one for the black image overlay and another for the cutout image. So it could also be done with shaders, though I can’t quite figure out how, even though I know it works.

daring cove
#

Why is this not properly calculating the angle from origin to position on the x-axis?

Trying to rotate an inverse kinematics segment towards a target position.
The angle is correct, but it does not go negative when the position is infront of the segments origin.

public static float Follow(Vector3 origin, Vector3 position)
{
    Vector3 direction = position - origin;
    direction.Normalize();
            
    float ikAngle = Vector3.Angle(Vector3.down, direction);
            
    return ikAngle;
}
latent latch
#

Mask is basically stencil shader anyway

twilit fox
#

It won't work with mask so far during my testing.

#

How do you all handle tutorials? For example, if you want the user to click only a specific button and prevent interaction with others, how do you manage that?

latent latch
#

Disable the elements you don't want targeted, or manually raycast and go through the list of elements and only apply work on the one you want.

lean sail
leaden ice
#

If you want a positive or negative angle, use SignedAngle

twilit fox
#

Seems like a little complicated like I would have to do this for each tutorial step, what do you think?

leaden ice
#

Seems like a pretty simple function to do that in code

#

that would only have to be written once

#

the only thing you'd need to do for each step is pick the set of controls you want to remain active

twilit fox
#

but what about the overlay like to indicate this button to click?

leaden ice
#

use the mask technique

twilit fox
#

so mask to visually indicate this button to click and using code to disable interaction on other buttons?

leaden ice
#

you could build a Bounds/Rect from the rects of all the elements

#

and then dytnamically shape the mask

#

yes

daring cove
leaden ice
#

Vector3.Angle gives you the shortest angle

daring cove
leaden ice
#

Vector3.SignedAngle gives you a signed angle

leaden ice
#

for an angle you need 3 points and/or two direction vectors

daring cove
#

The angle should be on the x-axis or any axis for that matter never more than one

leaden ice
#

It's kinda hard for me to get what you're going for without seeing a diagram or something, but with Vector3.SignedAngle you specify an axis to check the angle around

sudden ruin
#

help im been stuck at this for hours, dot know why the result vector isnt 90 degree to the incoming ray, the blue line is the surface hit.normal, trying with vector3.reflect

heres the code on the blue man if this help:

using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
public class Attack : MonoBehaviour
{
    public int maxReflections = 5;
    public float maxDistance = 100f;
    public LayerMask hitLayerMask;

    private LineRenderer lineRenderer;

    void Start()
    {

        lineRenderer = GetComponent<LineRenderer>();
    }

    void Update()
    {
        CastLaser();
    }

    void CastLaser()
    {
        Vector3 origin = transform.position + new Vector3(0, 0.5f, 0); // avoid ground
        Vector3 direction = transform.forward;
        List<Vector3> points = new List<Vector3> { origin };

        for (int i = 0; i < maxReflections; i++)
        {
            if (Physics.Raycast(origin, direction, out RaycastHit hit, maxDistance, hitLayerMask))
            {
                points.Add(hit.point);

                if (hit.collider.CompareTag("Shield"))
                {  
                    Debug.DrawRay(hit.point, hit.normal, Color.blue, 1f);
                    direction = Vector3.Reflect(direction, hit.normal).normalized;
                }
                else
                {
                    break;
                }
            }
            else
            {
                points.Add(origin + direction.normalized * maxDistance);
                break;
            }
        }

        lineRenderer.positionCount = points.Count;
        lineRenderer.SetPositions(points.ToArray());
    }
}


leaden ice
#

you're using origin as the start for even the reflected parts of it

#

for the second part, the new origin should be the previous hit point

daring cove
sudden ruin
#

thanks i will be need time to process this

lean sail
leaden ice
lean sail
#

from what im gathering here, it should reflect if it hits a shield. it makes sense that the end point would be the origin + direction.normalized * maxDistance and then they break; after

#

i feel like the blue line result makes sense, im not sure why a 90 degree angle would be expected there

leaden ice
#

What you Want is A -> B and B -> C

but you did A + the reflected arrow instead of B + the reflected arrow so you got D instead of C

#

So we got the green line instead of the purple

leaden ice
#

because origin is explicitly A in my diagram

#

it should be B + direction.normalized * maxDistance

#

And B will have been the hit.point from the first raycast

#

you cannot keep using origin

#

unless you update it for the reflected hits

#
Vector3 origin = transform.position + new Vector3(0, 0.5f, 0); // avoid ground```
This is the only time they're setting `origin` ^^^
#

it's the player's position, always

lean sail
#

ah I see what you mean about the origin part

leaden ice
#

I think they basically just need to do origin = hit.point; if there's a hit

sudden ruin
#

if (Physics.Raycast(origin, direction, out RaycastHit hit, maxDistance, hitLayerMask))
{
origin = hit.point;
points.Add(hit.point);

yes i update the origin and it works now

leaden ice
#

that might just fix it immediately

sudden ruin
#

so dumb

leaden ice
#

yeah

lean sail
#

the 90 degree part of the question confused me because im still not sure which part of this would be a 90 degree angle

#

but yea glad it works

leaden ice
#

it isn't 90 yeah - I think they meant that it wasn't reflecting properly over the normal

#

really it's angle of incidence == angle of reflection

sudden ruin
#

im having trouble reading you guys with my english but thanks !
i will try to go back to understand what happend back there, math skill not good

daring cove
#
public static float Follow(Vector3 up, Vector3 origin, Vector3 position)
{
    Vector3 direction = position - origin;
    direction.Normalize();
            
    float ikAngle = Vector3.SignedAngle(direction, up, Vector3.down);

    return ikAngle;
}

This is just calculating nonsense not even close to the specification

leaden ice
#

Vector3.down is the y axis

#

Vector3.right / left would be the x axis

daring cove
#
public static float Follow(Vector3 right, Vector3 origin, Vector3 position)
{
    Vector3 direction = position - origin;
    direction.Normalize();
            
    float ikAngle = Vector3.SignedAngle(direction, right, Vector3.right);
    Debug.Log(ikAngle);
            
    return ikAngle;
}

This also wrong I don't know what axis to give as a parameter

leaden ice
#

Is this a 2D game?

#

3D game?

daring cove
#

3D

leaden ice
#

some visuals would really help

daring cove
#

The red cube is the origin position or rightFootController.transform.position
The green cube is the target position or worldSpaceTarget

ProceduralAnimator.UpdateTargetHeading

Vector3 worldSpaceTarget = offset + rightFootController.transform.position;

rightFootController.TargetHeading = IKController.Follow(
    rightFootController.transform.right,
    rightFootController.transform.position, 
    worldSpaceTarget
);

ProceduralAnimator.OnDrawGizmosSelected

private void OnDrawGizmosSelected()
{
    Vector3 worldSpaceTarget = target + rightFootController.transform.position;
    Gizmos.color = new Color(0f, 1f, 0f, .45f);
    Gizmos.DrawCube(worldSpaceTarget, Vector3.one * 0.2f); 
    Gizmos.color = new Color(1f, 0f, 0f, .45f); 
    Gizmos.DrawCube(rightFootController.transform.position, Vector3.one * 0.2f);
}

IKController.Follow

public static float Follow(Vector3 right, Vector3 current, Vector3 position)
{
    Vector3 direction = position - current;
    direction.Normalize();
            
    float ikAngle = Vector3.SignedAngle(direction, right, Vector3.right); // 90 when it should be 0, because "position" is directly below "current"
    Debug.Log(ikAngle);
            
    return ikAngle;
}
#

ikAngle is logged as 90

#

And target heading is used in this way to rotate the inverse kinematic segment in local space

Quaternion targetRotation = Quaternion.Euler(axis * _targetHeading);
// axis is (1, 0, 0)
transform.localRotation = Quaternion.RotateTowards(
    transform.localRotation,
    targetRotation,
    RotationSpeed * Time.deltaTime
);
floral drum
#

anyone have tmp input fields work fine in editor, but dont let u use them in a build?

daring cove
# leaden ice some visuals would really help

This is one got really close but is ping ponging between -179, 179 after it reaches the angle. Also after rotating the armature it calculates it wrong again.

Vector3 worldSpaceTarget = target + rightFootController.transform.position;
rightFootController.TargetHeading = IKController.Follow(
    rightFootController.transform.up,
    rightFootController.transform.position, 
    worldSpaceTarget, 
    Vector3.right
);
leaden ice
#

it's rightFootController.transform.right

#

correct?

daring cove
#

Yes correct

leaden ice
#

also these seem wrong then:

rightFootController.TargetHeading = IKController.Follow(
    rightFootController.transform.right,
    rightFootController.transform.position, 
    worldSpaceTarget
);```
#

right wouldn't be one of the directions, and transform.position is definitely not a direction

daring cove
#

it calculates the direction

public static float Follow(Vector3 currentAxis, Vector3 current, Vector3 position)
{
    Vector3 direction = position - current;
    direction.Normalize();
            
    float ikAngle = Vector3.SignedAngle(currentAxis, direction, Vector3.right);
    Debug.Log(ikAngle);
            
    return ikAngle;
}
leaden ice
#

Alright but Vector3.SignedAngle(currentAxis, direction, Vector3.right); doesn't make sense if currentAxis and V3.right are the same direction vector

#

I think I'm still not clear exactly which angle you're trying to calculate

daring cove
#

the x axis

leaden ice
#

"the x axis" doesn't tell me anything really

#

you have this object which is facing.. down

daring cove
#

its rotated 90 degrees by the wrong calculation

#

normally its like this

leaden ice
#

An angle needs 3 points

#

two directions

#

what are the points/directions here?

#

(in this diagram the "axis" is pointing out of the screen through that "fulcrum" point

daring cove
#

The dots are points and the lines are directions

leaden ice
#

Yes now, what are the corresponding points and directions on your robot

daring cove
#

The top is Vector3.up
The bottom is the current
The right is is position

leaden ice
#

well the top is really current + Vector3.up

#

but a sa direction yyeah it's Vector3.up

#

so the two directions are Vector3.up and position - current

#

and finally what's the axis

daring cove
#

x axis

leaden ice
#

in the blue dots diagram it's pointing out of your screen

leaden ice
#

local x axis for some object?

daring cove
#

local x axis of the right foot

leaden ice
#

So then it should be this, right?

Vector3.SignedAngle(Vector3.up, direction, rightFootController.transform.right);```
daring cove
#

After swapping out Vector3.up to Vector3.down it works

fiery steeple
#

Hey, am I correct if I say that these are the steps to follow to make localization work in a game please :

    1. Install the Localization package
    1. Choose the languages I want to localize
    1. Create the Localization table
    1. Create entries and give them name for the key
    1. Fill those entries with appropriate translation for each language

In Code :

    1. Create a string variable that contains the name of the table ( i.e tableName)
    1. Create a string variable that contains the name of the entry (i.e tableEntry)
    1. Create a LocalizedString variable and instantiate it to a new LocalizedString(tableName, tableEntry);
    1. Subscribe to StringChanged for the localized string variable in OnEnable()
    1. In OnStringChanged method, change the UI text there by assigning the parameter localizedText to it
lean sail
fiery steeple
#

And i already read the doc it didn't help me that much

lean sail
# fiery steeple It's not an AI list, I made the list myself after struggling to implement it the...

i see, i dont see anything wrong with the steps at least so i believe its fine. It just seemed like AI because its very focused on stuff you probably dont need in a guide. Like the "in code" steps 1 and 2 surely can be excluded.
Also https://docs.unity3d.com/Packages/com.unity.localization@1.0/api/UnityEngine.Localization.LocalizedString.html localized string doesn't have to take string in the parameters according to the docs.

TableReference tableReference
Reference to the String Table Collection. This can either be the name of the collection as a string or the Collection Guid as a System.Guid.

TableEntryReference entryReference
Reference to the String Table Collection entry. This can either be the name of the Key as a string or the long Key Id.

fiery steeple
#

And how to get it ?

lean sail
#

you dont specifically need it here if what you have works

fiery steeple
#

Like I guess I need the name of collection and a special type to save that collection

lean sail
#

its surely somewhere on the UI but yea I didn't see it from skimming through screenshots on the docs

round violet
fleet gorge
#

!ide

tawny elkBOT
fleet gorge
#

fourth link

#

First time with rider? Or did it do this after an update

round violet
#

for unity kinda, im used to use it for c++ and UE

round violet
#

seems like a bug since i found the forum post mentionning it

#

or its this setting, which shouldnt be applied

#

yeah disabling "inherited values from" and "Foreground" fixs this

nova roost
#

Is there a way to lock a Script from any changes?

maiden fractal
fleet gorge
#

I assume you want your teammates not to touch certain scripts?

#

That's what version control is for, only accept commits that conform to the project standards

lone turret
#

anyone here familiar with Sprite.OverrideGeometry?
At runtime I'm trying to create a sprite. Just as a test I'm trying to only generate the top left triangle for the geometry, but this just gives me a normal rectangular sprite the size of the texture.

def = Sprite.Create(texture,//texture
    new Rect(0, 0, texture.width, texture.height),//rect
    Vector2.zero,//pivot
    32,//pixelsPerUnit
    0,//extrude
    SpriteMeshType.Tight,//meshType
    Vector4.zero,//border
    false);//genPhysicsFallback

def.OverrideGeometry(
    [
        new Vector2(0,0),
        new Vector2(0, texture.height),
        new Vector2(texture.width, texture.height),
    ],//vectors
    [0, 1, 2]);//triangles
#

it looks the same as when I don't call OverrideGeometry

nova roost
# maiden fractal but why?

I'm preparing a practical examination and I want the students to only change code in a single file, everything else should be Read Only

trim schooner
#

Put the stuff you don't want the to be able to edit in a .dll

nova roost
steady bobcat
#

remember that c# is easily decompilable so it wont obscure code well but should suit your needs

#

If you want code that cannot be easily "read" it will need to be done in c/cpp/other c abi compatible lang and compiled into a shared lib.

worn oasis
#

Is there a way to integrate a chatgpt agent into our unity project, like we would a package?

night harness
last quarry
#

Not a very tamper proof situation but unless they start copying things around it'll remain read-only, and as a benefit it'll be easy to read the code without decompilation.

thin aurora
#

I doubt this is on a level where they can do that anyway

#

I'm surprised the most simple answer was not given, just make a folder explicitly named "read-only" and put scripts there. Clearly indicate the scripts are to not be modified and if the student does so anyway then that's their problem

#

@nova roost

#

Unless your student supplies the final game in which case you can't compile yourself with proper files, then it's different

shadow wagon
#

you can get the satisfaction when a student complains their code doesnt work, and the cause was that they went and modified code in the "DO NOT EDIT THIS CODE" folder 😆

#

see it as an indication of which students can follow basic instructions

nova roost
#

.dll wont work because they should be able to check some of the code, but dont change it. I thought it would be great to put like a lock on this file (like office allows you to do) with an additional security check "you're not supposed to edit this"

vestal arch
chilly surge
#

You can also just reject the submission if it contains modification to files outside of the designated directory. Or make students only able to submit their files in said directory. Or treat all student submitted files as files in said directory.

vestal arch
#

i feel like making them actually readonly would be pretty easy but maybe that doesn't work with how you're distributing them?

nova roost
#

So my current plan is to give them a simple project where some functions are connected, but not implemented
so they have one file with a few empty functions inside that are being called from other scripts.
That way they only actually submit that file

brave geyser
#

That sounds like the easiest way.

lean sail
# nova roost So my current plan is to give them a simple project where some functions are con...

I think you are overthinking this and should just do as FusedQyou suggested here #archived-code-general message
I've had this same situation given to me on tests and assignments, just not in a unity context. Just make it clear they are read only and to not modify anything. State that you have your own copy of the files and will overwrite that folder with the original, so any changes wont be used. You'd be doing this anyways if you gave them files with empty functions. It might be more clear to some people what the functions are actually doing if they can skim the code

#

if someone modifies it still and their actual code has a compile/logic error after, thats entirely on them

modern epoch
#

how do i change the aspect ratio of the screen thru code

modern epoch
#

thx

sudden nymph
#

Can anyone help me with a delegate issue? I'm setting up some buttons in Start() and when I press the buttons later they don't work.

for (int i = 0; i < 13; i++)
{
  ResultFrame.Find(i.ToString() + "/Bet/Button+").GetComponent<Button>()
    .onClick.AddListener(delegate { IncrementBet(10, i); });
  ResultFrame.Find(i.ToString() + "/Bet/Button-").GetComponent<Button>()
    .onClick.AddListener(delegate { IncrementBet(-10, i); });
}

With debugging I see that all of the buttons when clicked later call IncrementBet(val, 13) with 13 being outside the range, this is because the delegate is pointing to the integer value i, which at the end of the loop is 13, right? How do I set that properly?

somber nacelle
steady bobcat
#

we gonna ignore that crazy find usage in the loop?

somber nacelle
#

i've mostly given up on trying to correct things like that because people hardly ever listen 🤷‍♂️

old path
#

how can I make it so the red bar is contained only in the card it's in

the red bar is spinning and it shouldn't show on the cards next to it

please help

#

the prefab looks like this
the 'ToHit' section is what conatins the bar and the black background

sudden nymph
steady bobcat
# sudden nymph What's wrong with it?

Finding by name is just unreliable and slow. You should use a serialized array or list instead and have it be the type you need already:

[SerializeField]
List<Button> buttons;
sudden nymph
#

Unreliable and slow for something that happens once during Start and is procedurally generated in the code?

chrome berry
old path
#

they're sprites and Im already using a SpriteMask, the problem is the cards kinda overlap on each other

chrome berry
naive swallow
#

Set those in the inspector

naive swallow
#

Or, if they're spawned in at runtime, add them to the list as they're spawned

sudden nymph
chrome berry
old path
#

okeeeee, thanks yet again

chrome berry
#

Oh, boxfriend's tutorial covered that, nevermind!

brave geyser
sudden nymph
bronze crystal
#

why my ai doesnt follow the ball, i use a prefab in the transform spot

#
        {
            GameObject ballObj = GameObject.FindWithTag("Ball");
            if (ballObj != null)
                ballTransform = ballObj.transform;
        }```
#

only when i drag the ball from the hierachy

#

[SerializeField] private Transform ballTransform;

#

but what if my ball isn't spawned yet

#

how to fix that

somber nacelle
#

prefabs do not exist in the scene, so naturally a prefab assigned to that variable won't be the one that is actually in the scene. you need to pass the reference when the object is spawned

bronze crystal
#

with findwithtag?

somber nacelle
#

ideally without using any of the Find methods. whatever spawns the ball can pass the reference to this object or can invoke an event

bronze crystal
#

i got rigidbody and 2d sphere on my ball but it doesnt collide

somber nacelle
#

how is it moving. also by "2d sphere" do you mean a "circle" collider?

bronze crystal
#

yes

woeful hamlet
primal gale
#

Aight im trying to make a simple flying enemy in a side scroller 2d game, and its currently able to be knocked back by bullets. Lets say I want it to drift back to its original position after being knocked back, how could that be done? Or even making it move back towards a programmed path it takes after being knocked back

#

could I just make waypoints along its path and have a coroutine check if its on them or not?

#

I was tihnking about using Vector2.MoveTowards but I think that ignores physics so maybe acceleration or forces?

steady bobcat
modern epoch
#

Screen.SetResolution isnt working for me

#

it wont change to landscape

#

nor will it change to portrait when in landscape first

#

    public void MoveToScene(int sceneID)
    {
        if (sceneID > 1)
        {
            Screen.orientation = ScreenOrientation.LandscapeLeft;
            Screen.SetResolution(2400, 1080, true);
        }
        if (sceneID < 2)
        {
            Screen.orientation = ScreenOrientation.Portrait;
            Screen.SetResolution(1080, 2400, true);
        }
        SceneManager.LoadScene(sceneID);
    }
steady bobcat
#

is this full screen or windowed?

modern epoch
#

windowed

#

so i have it portrait right now

#

starting from the title page

#

but when i go into the game it still stays portrait

brave geyser
#

your if statements are confusing and I am guessing not really what you want

modern epoch
#

oh is that why

brave geyser
#

It could be 'right'. It is just written in a way that looks like that's not what you intended.

modern epoch
#

no it still stays portrait when i change to "else"

#

is it because my editor resolution is a specific size

#

how do i go full screen

#

omg i have to pay to go full screen????

steady bobcat
#

er no? what unity version is this??

naive swallow
modern epoch
#

i googled how to go full screen and ppl said unity removed that feature

#

so i downloaded a github project for it

modern epoch
#

ok so anyway

#

i changed my aspect ratio to 4k

#

it shows everything fine but it's not what i wanted

#

my game is for mobile so it needs a specific ratio

#

im out of ideas

brave geyser
#

This is just running it in editor and you're trying to change this? I've never done that in editor before, so not even sure what that means in that situation. The orientation property is only for mobile.

modern epoch
#

Yes my game is designed for mobile

#

Android specifically

chilly surge
#

Mobile devices have many different aspect ratios, what should happen if your game is running on a device that doesn't match the one you want?

modern epoch
#

I set the resolution to full screen so it should be alright

#

The problem is it's not changing to landscape

#

Well it is in 4k

#

But how can I be sure

#

4k just has a large ass resolution that shows everything

#

Do I test on my phone?

chilly surge
#

You can change the resolution in editor game view.

#

If you don't want your game to run in portrait mode ever, you can uncheck them in project settings.

modern epoch
#

No my title page is portrait

#

And my game is landscape

#

Im just gonna test it on my phone

steady bobcat
#

yea you should verify this stuff on a device or an emulator

brave geyser
#

Using different resolutions in editor will be necessary, especially for your UI layouts. You can just use this to check with your gameplay (landscape) scenes.

fiery steeple
#

Guys, how hard will it be a for beginner++ to make a chess game (including the AI part) ?

brave geyser
#

8.86/10

leaden ice
#

But there are many guides out there for it

fiery steeple
fiery steeple
lean sail
fiery steeple
lean sail
fiery steeple
naive swallow
fiery steeple
night harness
#

Unnecessary to put another game down

#

Multi dimensional chess and shotgun chess are also really cool

fiery steeple
naive swallow
#

What is it?5D Chess With Multiverse Time Travel the first ever chess variant with spatial, temporal, and parallel dimensions. It's the first ever chess variant with multiverse time travel!

Features

  • Sharpen your tactics by solving a collection of multiverse chess puzzles.
    • Practice against four different AI personalities, each with different stre…
Price

$11.99

Recommendations

7372

▶ Play video
lean sail
#

spend 20 minutes on popular chess websites and you'll see just how many features there are

fiery steeple
naive swallow
fiery steeple
primal gale
#

How can I call my knockback code on my ai script? I want to be able to shoot my 2d enemy while its flying towards me but it currently does not take knockback since its locked out of it due to movement

#

I currently have both these scripts on the enemy

#

I cant call TakeDamage since it takes parameters and the update function is void

leaden ice
primal gale
#

My TakeDamage script does the knockback at the moment

leaden ice
#

ok, so call it

#

whenever the conditions happen in which you want it to take damage, call TakeDamage

primal gale
#

but takedmg calls parameters and I thought update has to be void

leaden ice
#

first of all void is a return type

primal gale
#

or have I been trolling myself

leaden ice
#

which has nothing to do with parameters

#

second of all i don't see why it matters what parameters or eturn type Update has

#

We're talking about calling a different function

#

where do you want to call TakeDamage from?

primal gale
#

the if statement

#

I was thinking about doing if !TakeDamage()

#

so if I was not taking damage at the moment the AI could freely move

leaden ice
#

🤔

primal gale
#

I dont know

#

im just spitballing here

#

I dont have a script that specifically calls knockback since I use it in the takedmg

leaden ice
#

What are you trying to do, I don't really understand. I guess you're saying you don't want that code to run if TakeDamage... happened... recently? This frame?

#

SOmething like that?

primal gale
#

something like that

leaden ice
#

you would communicate whatever information you need to communicate through variables

round violet
#

How does reflected/reserved functions in monibehaviors such as OnTriggerEnter are called/registered when the "event" (in this example a physics event) happens.

Is it a delegate registration on game init ? Or something more dynamic running on each event occurrence

leaden ice
#

then you would do if (!tookDamageThisFrame)

primal gale
#

yes thats what I was thinking

leaden ice
#

and you would set it to the appropriate value at the appropriate time

primal gale
#

I use that in my gun recoil script btu wasnt sure if it applied here

round violet
primal gale
#

pkay hold on I think I can figure it out

leaden ice
primal gale
#

I just wanst using my brain folds

round violet
#

Probably micro optimization but id rather ask then discover it to late

leaden ice
#

the method reflection info only takes memory once

#

If you are having a framerate issue, you should use the profiler to find the bottleneck.

round violet
leaden ice
#

Whaqt do you mean

#

the game engine certainly keeps a collection of all the objects in the scene

#

it simply iterates over that

round violet
leaden ice
#

if you don't have much time, you should be focusing on the game design and implementation

naive swallow
leaden ice
#

if and when you find a performance problem, then you use the profiler and see what the issue is

round violet
# leaden ice Whaqt do you mean

You said the reflection system gets only one "instance" of a mono.
So im wondering how the physics engine communicates on physics event

leaden ice
#

not of the mono

round violet
#

Ironically

naive swallow
round violet
#

Wasted a day on ECS, but wasnt suited for a short notice

leaden ice
# round violet You said the reflection system gets only one "instance" of a mono. So im wonderi...

The physics engine doesn't know anything about monobehacviours etc. the game engine has a mapping beteween physics object IDs and UnityENgine INstance Ids. when it gets notifications about collisions etc from the physics engine it looks up the corresponding Unity objects via instance ID then uses its internal SendMessage system to call the function. The messaging system is the thing that cares about methods existing or not on MonoBehaviours

round violet
leaden ice
#

nah

#

this kind of refactor is really simple typically

#

like - moving something from an Update loop to another loop

round violet
#

Its a core process in my game, refactoring it will take some time

leaden ice
#

very simple, just make sure you're following good coding practices like putting stuff in modular methods etc

#

anyway I've said my piece - you are most likely prematurely optimizing.

round violet
leaden ice
#

there's also very little youi can do about physics callbacks

#

those have to run on individual objects if you're using Rigidbody/OnCollisionXXX etc

leaden ice
round violet
#

You said something gets the physics engine notifications and gets the corresponding mapped unity object id from the physics id to call the event on the mono instance

leaden ice
#

yes

round violet
#

So, in a way its a rereoute

leaden ice
#

that happens whenever it has notifications to send

#

but it's not doing refflection there

#

it's basically a bunch of C++ std::map calls most likely?? It's a closed source part of the engine so we don't know.

#

it's fast

round violet
#

I forgot this sad part of unity

#

I guess ill put them on the Object B, and hope it fine enough

#

Thanks for the insights!

leaden ice
#

not in terms of performance

#

What might matter is if you can make it so one of those objects actually doesn't ahve a script on it at all

#

that would save memory

#

but if they both have scripts on them and you're just deciding which one to put the message on, you should make that decision based on code design principles.

round violet
leaden ice
#

you can't

oblique spoke
latent latch
#

Collider is the problem not so much the OnTrigger ;p

leaden ice
#

Unity requires callbacks on the object itself

round violet
#

I guess its a limitation of this reflection system design

#

I also wonder how much it costs for the physics engine to add/destroy a collider component frequently (or move it between parent gameobjects if this is possible?)

#

And last question because im really tired, but thanks to you guys tomorrow will be less painful: would a raycast per frame be the same as the process of moving an object with a collider ?

latent latch
#

Unity physics operates mostly in the fixed loop and interpolates a lot of that information, as doing it per frame would probably be very costly with that many units

round violet
#

Let me rephrase it: If we take 1 object doing 1 trace per frame
VS
1 object moving around with a collider

What takes the more frame time ? For the physics engine

latent latch
#

but doing queries yourself doesnt have that continuous collisional detection that rigidbodies do come with, so you're usually having to implement some extra logic to prevent cliping through objects

round violet
#

In my case its a simple "on trigger enter run some code then destroy myself"

latent latch
#

I would think doing queries would be quicker, but that's just because there's extra work to be done with what's offered with the physic (rigidbody) solutions

round violet
#

I also wonder if editing the transform component is the correct way of moving a GO with a collider if no CC or RB is used

vestal arch
rigid island
#

this isn't the place for that. collab 👇

tawny elkBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

dim cairn
#

forget starving artists, now we have starving coders

ripe yoke
#

Ye I tried

night harness
#

There’s no equivalent to a destroycanceltoken for just a gameobject right?

last quarry
round violet
#

is there any recommended/consensus on a free hot reload plugin ? (that ideally doesnt take a lot of setup to make it run properly)
domain reload on each play is killing my time

cold parrot
round violet
#

so everyone in the industry is waiting 10-20s before each play test ?

cold parrot
#

some people report deriving some productivity benefits from them in certain situations (i suspect these are small-ish projects that don't make use any unsupported changes regularly)

round violet
#

i get the productivity thing for the initial code compilation, not for the play compilation

cold parrot
#

i would say iteration time is ~30-60 in an average mid-size project and much more in large ones.

round violet
#

ill be honest, seems completely dumb

cold parrot
#

you can disable domain reload

round violet
#

maybe no hot reload plugin are perfect but im sure some are good enough to gain time

round violet
cold parrot
round violet
#

or global shared vars across pooled objects

cold parrot
#

strategically you can develop your project in a way that you do most of the game-content-creation without code changes, this speeds things up when you also disable domain reload

round violet
#

thats perfect

cold parrot
#

the more statics and OnValidate stuff you have the slower the project will be.

round violet
#

its ironic that i thought unity would be better than UE because compilation is in editor, but it seems that it isnt the case (probably because of having the whole project code in a single assembly)

cold parrot
night harness
#

You can split your project up into different assemblies if you want

round violet
cold parrot
round violet
night harness
#

Yee

cold parrot
round violet
#

yeah, but you still have medium to big assembly at some point because you cannot split everything to tiny stuff

#

for example the player stuff

#

per header update in c++ is nicer imo

cold parrot
#

you need to have one core-assembly that references everything and manages communication, then everything else can be in layer-assemblies below that

round violet
night harness
#

Hopefully there’s maybe some improvements to compilation once we finally get coreclr

cold parrot
round violet
#

im on mono already

#

my cpu isnt great tho, r7 3700X

cold parrot
#

doesn't matter that much

#

fast SSD helps

#

but really the best you can do is develop some knowledge and intuition what slows down projects. stuffing everything in one place certainly does.

round violet
#

aside from static stuff, what can be an issue if i disable domain reload ?

#

is editing props and stuff like that an issue ?

cold parrot
#

its primarly about statics and other similar things that are already loaded in editor. You need to be careful with your pools.

#

most (tentatively all) stuff that is part of serialization gets reset by the serializer and doesn't need a domain reload

#

You're also more likely to have memory leaks.

round violet
#

from editor or my own code ?

#

im also wondering it this "reset statics on start" is something i should only have in editor, or also in packaged game

steady bobcat
#

A better cpu does help too, I have a 7950x3d, my play domain reload takes about 5-10 s depending on the project.

last quarry
#

Gonna have to do this stuff in Unity 7 anyway since domains are going away

round violet
#

yeah, but im not waiting for unity 7 😅

last quarry
#

Yeah just disable the domain reload and see what bugs crop up. It's managable

round violet
last quarry
#

That's unnecessary. The domain isn't kept between runs of the built player anyway

trim schooner
#

There's something weird going on with my Unity + VS.. I'll double click a script in Unity to open it, and sometimes VS will close all the already open scripts so it's just this new one open

true swan
#

can someone explain to me why I'm having this issue image 1 but my code says this I assign the target pos to the agents destination

steady bobcat
#

I have no idea what you mean 😆
targetPos is not shown in the watch/locals window

round violet
#

can i have .h/.cpp like file seperation with unity .cs files ?

#

i like navigating in a not crowded header when im looking at the structure of a type

sharp temple
#

Anyone knows why the character controller in unity 3d doesnt prevent the player from walking on a higher angle slope than the max slope angle? Im using unity 6.1.. something 2f and i dont know if its a bug because in unity 5, my code used to work flawlessly

last quarry
#

Unity 5?

sharp temple
#

Yeah

last quarry
#

Do you mean 2022?

sharp temple
#

Yeah 2022

last quarry
#

Aight, just checking you didn't just put your project through a decade of editor updates

sharp temple
#

Its not the same project but the same movement code

thick terrace
last quarry
#

Is this Move or SimpleMove?

sharp temple
#

I never use simple move

#

I dont know if its a bug with the new version cuz it used to work in my other project in unity 2022

last quarry
#

Works fine for me in 6000.0.47, is all I can say.

sharp temple
#

Ok

#

Ill do some testing when im home

#

Cuz rn the player can climb anything not perfectly inclined 😭 🙏

last quarry
#

There's been some physics changes in 6.1 so maybe it is bugged

sharp temple
#

Ill check in unity 6.0

#

If it works fine

round violet
#

how does c# memory works with scope ?

for example, if i make a struct instance in a function scope, then pass it by ref to another object that store it in a member variable, will it be still pointing to the correct address or will it be garbage memory ?

last quarry
#

Assigning the member value would be a copy operation

#

Unless that is also a ref struct

round violet
#

it will be a ref struct

#

from what i understood the c# GC will only clean it if its not referenced, i assume storing it in a living class in a member var is enough

#

i dont know if unity does anything more special though

late lion
# round violet can i have .h/.cpp like file seperation with unity .cs files ?

If you don't care about breaking common C# code conventions, you could use the partial keyword to achieve this.

Dog.h.cs

public partial class Dog
{
    public partial void Bark();
}

Dog.cs

public partial class Dog
{
    public partial void Bark()
    {
        Console.WriteLine("Woof!");
    }
}

But no one does this. More commonly, interfaces and abstract classes serve this role.

round violet
#

thanks for the example !

last quarry
round violet
#

but you are right, its better if i get use to it

last quarry
#

There's no garbage collection on structs

round violet
#

is GC only for classes ?

last quarry
#

Only for heap allocations

#

So arrays too

#

Strings

thick terrace
#

ref structs have special usage rules to avoid danging references, it's statically enforced

round violet
#

so i should get a warning on compile if my struct ref would be lost ?

last quarry
#

No it wouldn't be allowed to leave the scope of the stack

thick terrace
#

it wouldn't compile if there was a chance to have a ref to something invalid

last quarry
#

Just no compilation

#

Like you can't use them in lambdas

round violet
#

basically i want to do this:

// Object A

SomeFunc
{
   var data = new Data(); // could be class or struct
   SomeObjB.SecondFunc(ref data)
}

// Object B

protected Data dataM

SecondFunc(ref data)
{
   dataM = data; // i guess here its a copy ?
}
thick terrace
#

yup, it's a copy

last quarry
#

You could do protected ref Data dataM instead

round violet
#

i cant, says c# version is to old

last quarry
#

Of course it is

round violet
#

Please use language version 11.0 or greater.

#

idk what version of c# unity 6 handles

last quarry
#

Old

round violet
#

this will never change sadblob

last quarry
#

Version 9

thick terrace
#

c# 9, with an asterisk (some missing library support for stuff like init properties)

#

it's not THAT old!

late lion
last quarry
round violet
#

but if its a class and not a struct, ref shouldnt be needed ? is doing dataM = data still a copy with a class ?

thick terrace
#

classes are reference types so every reference to them is a reference (a pointer)

last quarry
#

*a pointer, but safe

round violet
#

how are they cleaned ?

night harness
#

one day i will get my static defaults in interfaces

last quarry
#

Garbage collection

round violet
#

so i should be fine if i store my new Data object in dataM

late lion
last quarry
#

Why is the ref there anyway? Is it a particularly big struct?

round violet
#

yeah

#

big init struct i want to pass around without copies

last quarry
#

Use a class then

thick terrace
#

fwiw you can use in instead of ref for the equivalent of const &

last quarry
#

It's not garbage collected if the reference stays alive

round violet
#

class Data { }

// Object A

SomeFunc
{
   var data = new Data();
   SomeObjB.SecondFunc(data)
}

// Object B

protected Data dataM

SecondFunc(data)
{
   dataM = data; // not a copy, dataM refernces the Data object
}

?

round violet
#

😅

thick terrace
#

well there's out too, ref could be inout but i don't like that name either lol

last quarry
#

Yeah you'll want a class here. Usually stack allocations are for things that don't live past their function

#

Even in C++ I'd heap allocate this to be safe. In C# it's just mandatory to make a reference in this case.

late lion
#

A more memory efficient approach is to expose the dataM field and allowing Object A to write directly to it. Then there's no need for a copy. But that can go against encapsulation.

round violet
#

where is there a copy ?

last quarry
#

Seems to get inlined

late lion
last quarry
#

Presumably

late lion
last quarry
thick terrace
#

if it was a big struct, that's when making the parameter to SecondFunc a reference (ref or in) would be useful, i'd rather do that than expose a public field

chilly surge
#

(Do be careful about defensive copies with in though, that would nullify the whole point)

thick terrace
#

yeah, that's a difference from C++, where you can't call anything except const methods on a const reference, in C# it just causes a copy so you'd either need to make the struct a readonly struct or be careful to only call readonly methods

chilly surge
#

I'm using WebCamTexture for QR code scanning, on mobile with modern cameras it's taking a lot of memory, how would I go about reducing the memory usage (since QR code scanning doesn't need that high resolution)?
I can see that it has requestedWidth/requestedHeight properties, but how do they behave? Do I need to set one of them, or both of them? What values should I set them to? If a device has multiple cameras (eg main and selfie camera), would it match the selfie camera which I do not want?

late lion
late lion
#

As for how to choose the camera, I imagine you have to enumerate WebCamTexture.devices to find which ones are rear facing.

#

There you can also get the available resolutions and what kind they are (wide angle, telephoto, ultra wide).

chilly surge
#

Oh I don't mean that I want to pick a specific camera, it seems like the default already picks the rear camera which is what I want. It's just that I'm not sure if requesting a width/height would cause it to pick a different camera.

late lion
#

Each lens on the back of the phone will be represented as a separate webcam in this, so for most modern phones, you have 2-3 rear facing cameras to choose from.

late lion
# chilly surge Oh I don't mean that I want to pick a specific camera, it seems like the default...

If you're using the method overload that doesn't specify the device name, I would guess it would continue to pick the same camera. Unless the documentation specifies otherwise, I wouldn't assume that every phone will default to a reasonable rear camera. Unity just says it picks the first one.

If no device name is supplied to the constructor or is passed as a null string, the first device found will be used.

chilly surge
#

Yeah it just feels like there's a lot of guess work and hoping the API works the way we assume.

late lion
#

You can eliminate the guess work by enumerating the devices yourself and implement your own fallback logic. Maybe your first choice is a rear facing camera of the wide angle kind. If that doesn't exist, look for a rear facing ultra wide, etc.

chilly surge
#

Right that feels like what I have to do, by going through all the devices and their resolutions, pick the smallest resolution rear camera.

late lion
#

Well, you probably don't want to pick the ultra wide or telephoto lens over the wide angle, even if their smallest resolution is a bit smaller. A very low resolution ultra wide might not have enough resolution to scan the QR code and the telephoto lens might be too zoomed in for the user to scan at a comfortable distance.

chilly surge
#

Oh good call.

round violet
#

from a list of capsules (each representing a player), how would you try to get a free space next to one of them ?
my idea for now is:

  • for each capsule
    • get position, and do 8 CheckCapsule (add a angle delta between each check, imagine a circle cut in 8 parts) + some position delta
    • if one check returns true stop here
chilly surge
# late lion Well, you probably don't want to pick the ultra wide or telephoto lens over the ...

Eh, even the WebCamKind is unreliable on Android.

On Android devices, the hardware does not report this value, so Unity determines the WebCamDevice.kind by calculating the Equivalent Focal Length from a calculation based on the reported focal length and matrix size. Therefore, on some Android devices, the default camera may be detected as WebCamKind.UltraWideAngle or WebCamKind.Telephoto.

late lion
# chilly surge Eh, even the `WebCamKind` is unreliable on Android. > On Android devices, the h...

If it's at least based on the focal length of the camera, then you can still trust it to tell you how zoomed in the camera is. And whatever focal length Unity determines "WideAngle" to mean, probably similar to what it is on iOS, is still going to be your preferred focal length for scanning. So if some weird Android phone has very zoomed in lenses, such that it's ultra wide gets reported as wide angle and both the wide angle and telephoto are reported as telephoto, you'd prefer to use the zoomed in ultra wide.

#

And if some Android phone has no camera reported as wide angle, that's where your fallback would come in and you pick the second best option.

chilly surge
#

Yeah I'd have to actually grab a few phones and test them out to see what the best approach is.

#

It's very annoying for these kinds of stuffs, because what works for 99% might not work for the last 1%, and if you change something then a new kind of problem happens for new 1%.

late lion
chilly surge
#

Yes, but I'm not sure if Unity reports stuffs like AVCaptureSessionPreset640x480 as resolutions of the device or not.

#

That iOS native API presumably is using the same camera but capture with downscaling.

#

Actually, if Unity does report them as available resolutions, then 352x288 might be too low res for QR code scanning.

#

I guess I'll just have to grab some devices and check out how the API behaves.

late lion
#

I can't say from experience, but I feel confident that availableResolutions is pretty much going to be 1:1 with what the native APIs are returning. Unity won't be doing any of its own downscaling or anything, just for performance sake.

chilly surge
#

I wouldn't expect Unity to downscale either, but I'm thinking the issue is that the iOS native API provides resolutions down to 320x240, which is probably too low res for QR code scanning, so on top of the camera kind heuristics I have to also set a minimum size, and fallback if somehow a device only has camera that is really that low res.

round violet
#

when are input events (new input system) callback sent compared to Update/FixedUpdate/LateUpdate ?

tiny delta
#

Howdy there folks! I'm reworking my spell system in my game and I was wondering what is typically a good way to structure that sort of thing.

Currently I am using a scriptable object with a few enums to select between different "effects" - for example there's a SpellSpawningArea enum, and then in the SpellMovement script on the spell prefab it determines where to start based on that selection. However, I'm worried this is going to lead to bloat as I add more spell types including ones that operate in more unique ways (such as having many different types of movement for spells).

Alternatively, I could make the scriptable object contain a unique script for the spell that's attached onto the prefab when it's instantiated or even just have a unique prefab for each spell. But then I have to create a unique script or prefab for each spell which also seems like a bad idea.

Which way do you all think is better to structure this, or is there another way that you think would work better?

latent latch
#

Prefab workflow works, but otherwise you can make a single Spell prefab and throw SOs at it

#

Stick to composition if possible and not split out your logic into multiple classes

#

Edge cases can be easily avoided with a simple comparison

tiny delta
#

What do you mean don't split my logic into multiple classes?

latent latch
#

You can dig yourself a hole pretty easily with inheritance

tiny delta
#

But won't using just one class just lead to having one crazy long script with too much going on?

latent latch
#

Well, all the code doesnt need to be in one script, but yes.

tiny delta
#

How do I split up a class into multiple scripts then?

latent latch
#

Component workflow, have a list of behaviour that it executes

naive swallow
#

You take some of the stuff in this file, and put it in another

latent latch
#

So for example you want some movement behaviour, well my idea would be create a subclass/SO called SpellMovement where you've different variations such as standard linear movement or different types of trig methods for wave movement. So in your Spell class you'll have a list of SpellMovement that it'll read from in your update loops.

#

Which you can blend together to make your own patterns from multiple of these modules

tiny delta
#

So I'd have a main Spell class, which then calls MoveSpell, and then MoveSpell determines how it moves based on something else? Or am I misunderstanding

latent latch
#

If you want to shorten this script, that would be the idea yes. I usually like to throw in a bunch of animation curves and stuff to blend together for movement

#

Now, if you don't populate your SpellMovement list at all, then the Spell doesnt need to execute anything to move and you can consider it as some stationary spell

tiny delta
#

Ah, gotcha.

#

That makes sense for movement, and so I assume for a spell that is attached to a player I would have some sort of bool in the scriptableObject that determines whether or not it should be childed to a player object?

latent latch
#

What's the usecase for being childed?

#

You could give it the transform position

tiny delta
#

I have a dash spell for example, which moves the character and shows particles behind them

latent latch
#

Personally I'd handle that as an independent type of feature not so much a spell, but say that the dash did do damage to enemies then yes I would make a isLocal to source bool

#

So you'll have to invoke your method with parameters such that CastSpell(SourceEntity entity, Vector3 location, Vector3 direction) at minimal even if you don't need to use all parameters

tiny delta
#

Makes sense

#

So what type of objects would be in the SpellMovement list?

latent latch
#

If you did have spells that directly targted enemies, then you'll need to make an override probably and make one with the target entity

#

or just make a bunch of default parameters that you check is null

tiny delta
#

Makes sense, I could always just have a parameters that are like "CastSpell(Vector2 startPosition, Transform targetEntity)"

latent latch
#

SpellMovement can be SOs or some C# class, doesnt matter too much. You could nest it too inside of Spell but if you wanted a smaller script it's best to do that elsewhere. SOs are nice cause it prevents too large of an inspector to scroll through

tiny delta
#

So would I just have an Enum in SpellMovement that determines the movement type? Obviously some of them can be easily done with a formula, but some are pretty unique

latent latch
#

Sure, that works, otherwise you could derive more and do like SpellMovementWaves, SpellMovementHoming

#

enum works too

tiny delta
#

What do you mean by "derive more"?

latent latch
#

inheritance

#

yeah I said dont use it, but it's fine for components ;p

#

it's that or enums honestly