#šŸ’»ā”ƒcode-beginner

1 messages Ā· Page 260 of 1

rare basin
#

huh?

#

that's a fact

vagrant lynx
#

Hmm I see, thanks for this guide bro

quartz mural
woven crater
#

can i check for multiple tag? return true if one of them is found

quick summit
#

hello im new to unity and i have tried to figure this out for so long. So i have been trying to make a watermelon game where you launch it, and the further you go the more money you earn. i have made 2/3 out of all the sprites but i'm trying to know how to add a force to the catapult and also give it like a swing motion so it would launch it.

buoyant knot
woven crater
#

the other way around

rich bluff
#

have both lists have equal amount of elements

woven crater
buoyant knot
quartz mural
#

oh sorry i meant

rare basin
quartz mural
#

when an index is null

rare basin
#

and not extendable at all

#

if you want to add more obvjects

buoyant knot
short hazel
woven crater
#

oh or

buoyant knot
#

you would want to make a common component that stores Tag-like information to identify wtf something is and does

rich bluff
# quartz mural when an index is null

ensure that the objects you previously put into the list arent being destroyed, or just remove nulls after the objects are destroyed if thats the intent

short hazel
#

And don't forget to put the ORs in parentheses because they have lower precedence than the ANDs (like addition has less precedence than multiplication)

rare basin
woven crater
#

šŸ‘ ty

buoyant knot
#

EntityData : MonoBehaviour, give it a bunch of
public enum Shape { Box, Circle…. }
[field: SerializeField] public Shape geometryType {get; private set; } = Shape.Box;

Then GetComponent<EntityData>()

rich bluff
#

@buoyant knot about your question, why 1 per frame? whats the idea? i can imagine a scenario where a single keypress would send several commands that have to be queued

quartz mural
buoyant knot
rich bluff
quartz mural
#

thank u

#

so i have to fix from inspector

buoyant knot
#

or i am holding draw then press undo and rotate hotkeys on one frame. Q: What happens?
Currently a mess

rich bluff
#

that is the responsibility of the input system, to lock contexts

buoyant knot
#

what do you mean? you mean my code?

rich bluff
#

your input system, its not necesseraly command based

quartz mural
buoyant knot
#

yes, I want to use a command pattern to receive commands, and produce a single coherent result on each frame

rich bluff
#

similar to unity/rewired maps, there are input contexts which you enable depending on situation

#

which stack

buoyant knot
#

i’m confused. you mean inputsystem has a way to do this?

rich bluff
#

so if you start dragging, you push a dragging context and any keypresses like undo/redo would be ignored because they are not part of the dragging context

#

no i mean your code

buoyant knot
#

maybe explain to me what I should do so I can follow

rich bluff
#

unity input system would be the underlying implementation of the this concept

buoyant knot
#

right now, I have an InputAction asset, PlayerInput, and BuildInput class which subscribes methods (function of ImputAction.CallbackContext) to performed/started/etc

#

from here, what are you suggesting I do to make the different input actions able to cancel each other (or something like that)

rich bluff
#

can they be activated/deactivated simply? so they would unsub completely and not invoke anything

#

im thinking in terms of editor design so, context map would be something like

buoyant knot
#

i feel like that will turn into spaghetti, because now I need to juggle subscriptions from every possible input

#

some hotkeys are a one-frame thing. Some hotkeys are going to be a drag sort of thing

short hazel
#

You can have a Stack<?> that when you push something onto it, it disables an input action map, and when popping it, it enables it back again

rich bluff
#
- Main workspace
  - Viewport active - overrides hotkeys that overlap with main workspace
   - Drawing tool - disables main hotkeys, while keeping viewport hotkeys
#

if implemented like a stack with some rules, any time you click on the viewport, its context is pushed to the stack and anything below it should either deactivate or follow rules, click away and its popped from the stack, restoring previous state

torpid dust
#

I disabled normal and tangent. And every time I run the project, it puts it back and then tells me that I shouldn't be doing it. I don't understand.

buoyant knot
#

i was thinking having:
enum flag Command
struct CommandState {
Command started
Command held
Command released
}
lastFrame’s command state
this frame’s command state.
A static function of last frame and this frame’s CommandState that tells us: 1) Active command, 2) if that command should count as initial press or held, 3) a command we need to register as releasing

#

but idk if this is overcomplicated, or if there is a smarter system

rich bluff
#

its pretty simple approach and it will suffer from overlaps in various uses cases

#

its a good start

buoyant knot
#

i’m not defensive, just wondering since I’m still brainstorming

rich bluff
#

you dont keep state history to which program can return to, its destructive

#

so if something unexpected happens and it will, this will lead to various "stuck input" and so on

short hazel
buoyant knot
rich bluff
#

by state i mean editor state, like which windows are opened, which viewports and tools and so on

swift crag
rich bluff
#

as these things get very complex the state configs at various points tend to overlap

buoyant knot
#

i’m not sure I understand how it breaks.

#

do you mean the magical static method I wrote would get complex?

rich bluff
#

no it remains simple, the editor grows complex, so a simple method may not fit into scenarios that need you to abort/return to previous state

#

or, when you need to make decisions on priorities

buoyant knot
#

I am thinking the priority would be defined by the value of the flag enum.

swift crag
#

A stack will allow you to have an arbitrarily long sequence of command states.

buoyant knot
#

but then I can’t unpress something in the middle of the stack? unless I don’t understand what you mean for the stack representation

rich bluff
#

if its a command queue+stack i view it separately from input processing

#

a command is created from an input, or created by script

buoyant knot
#

i’m just confused right now

#

input actions invoke methods

rich bluff
#

that is implementation detail

buoyant knot
#

yeah, but the input action invocation creates a new (some object) onto (some data structure) that registers it has fired.

#

And then I need to parse it in some non-asenine way

rich bluff
#
base input system (Inputv1/v2/rewired)
  your input context/filtration code 
   generates editor commands

game/editor/network code 
  generates commands

data 
  txt scripts or anything, generates commands

command system (receives commands)
buoyant knot
#

the idea is to make a class where my editor queries it to ask ā€œwhat command to do now?ā€

#

if I can get that information into my editor class, I can take it from there

#

but the ā€œinput receiverā€ class needs to receive info from inputsystem to update internals to make a coherent response to that question

rich bluff
# buoyant knot but the ā€œinput receiverā€ class needs to receive info from inputsystem to update ...
class CommandCtx
{
   List<Type> allowedCommands;
   protected void Allow<T>()
    {
      allowedCommands.Add(typeof(T));
    }
}

class CommandSys
{
    Stack<CommandCtx> contexts;
    Queue<Cmd> commands;
    public void Push(...) ...
    public void Pop()
    {
        contexts.Pop();
    }
    public bool TryExecuteNext() {
        Cmd next = commands.Dequeue();
        // filtering
        if(contexts.Peek().allowedCommands.Contains(next.GetType())
            return Execute(next);
       return false;
    }
}

class DragCmdCtx : CommandCtx
{
    void DragCmdCtx()
    {
      Allow<StartDrag>();
      Allow<AbortDrag>();
      Allow<CompleteDrag>();
    }
}

// start drag
CommandSys.TryExecute(new StartDrag()); // fail
CommandSys.Push(new DragCmdCtx());
CommandSys.TryExecute(new StartDrag()); // success
CommandSys.TryExecute(new CompleteDrag());

just as illustration

buoyant knot
#

wow. big effort. ty

#

let me look through it rq

rich bluff
#

you can do it with enum, but its hard to extend locally

swift crag
#

although that was a queue, not a stack

buoyant knot
#

give me a hot minute. the architecture is very different from my initial vision, so it needs to sink in

swift crag
#

actually it's very much divorced from how that worked lol

rich bluff
buoyant knot
#

that is what is confusing me right now

#

i don’t understand why.

swift crag
#

A context is a situation you're in. Your current situation is the most recent context.

buoyant knot
#

because i would expect the list/collection of commands to be effectively constant, and the contexts change

swift crag
#

A command is a thing you tried to do. Your current command is the oldest command you haven't handled yet.

rich bluff
#

stack is a very simple solution, a robust solution is a graph

buoyant knot
#

oh you queue them because you want to still execute it if valid, but later

rich bluff
#

colony sims, city builders with lots of windows have to return not hierarchically, because you can have many identical windows open

#

so there has to be a graph that remembers the path to previously opened/focused context

buoyant knot
#

i’m really confused about this combo of stack and queue, sorry

rich bluff
#

simple editor with panels, like unity, you open a modal window, it is hirarchically on top of everything, so its on top of the stack

#

it catches all input

#

as soon as you close it its popped

#

so everything returns to how it was before

#

you open sevaral same windows, they open on top of each other pushed into stack, only top of the stack is processed

#

piramid basically

buoyant knot
#

but you have a queue of the commands, and stack of command contexts, because you want to do the most recent commandContext if it is possible

rich bluff
#

yes commands can come from many different places, not all should execute if the context doesnt allow it

buoyant knot
#

but let’s say I press draw, press undo, then release draw, release undo

prime lodge
#

hi i have array called weapons that is a as a class gameobject and iam trying to SetActive actual weapon but unity tells me this and i dont know really how event work yet

buoyant knot
#

now I would pop a draw contex which is not valid?

buoyant knot
rich bluff
#

guess a simple way would be for a command to track which context it originated from

swift crag
rich bluff
#

if that context is no longer valid dismiss it

swift crag
#

SetActive returns void, meaning that it doesn't return anything at all

buoyant knot
#

second, set active returns void, and you are trying to assign active weapon to a void, which makes nonsense

prime lodge
#

yeah it makes sense now

swift crag
#

I think you should have a List<Weapons> that you loop over, rather than a List<GameObject>, which it looks like you have

#

(maybe rename that to Weapon)

#

activeWeapon should be a Weapon, not just some random game object

#

and weapons should be a list of Weapon, rather than a list of literally anything in your scene!

rancid tinsel
#

Is there some function in unity to check what OS the game is running on or what OS the build is for?

#

I want to add a keybinding option for PC only

swift crag
#

yeah, look at the Application class

rancid tinsel
swift crag
#

you shouldn't need to distinguish between windows/mac/linux

rancid tinsel
swift crag
#

(i build for all three platforms and the only platform-specific code I have is for opening the log directory)

rancid tinsel
#

what are these 3 for?

swift crag
rancid tinsel
#

thank you

swift crag
#

windows store apps are distinct from regular Windows applications

#

in ways I don't really know about

#

something about UWP

honest vault
#

is there anyone that has 1 min free time to explain something to me?

silk night
#

UWP apps have some integration into windows and can use certain functionality

silk night
rare basin
honest vault
honest vault
rare basin
#

if its even being called

honest vault
swift crag
#

these pages will walk you through all of the possible problems

rare basin
honest vault
rare basin
#

then its not being called

honest vault
rare basin
atomic sierra
#

how do I avoid blindly following tutorials to learn how to make certain features or styles of games? Like I'm following a brackeys tutorial on how to make a tower defense game, but I know that I might end up seeing things I've never seen before, and I don't want to end up just blindly following the tutorial without understanding any of the code or features in Unity.

wintry quarry
#

Then take those learnings and apply the techniques yourself

silk night
#

You wont have a 1:1 tutorial but rather smaller problems to look up

atomic sierra
#

oh i c

swift crag
#

This will mostly come with experience.

silk night
#

In the latter you should watch it and the try to recreate the code instead of 1:1 copying it

swift crag
#

It's a bit hard for me to give advice here because I started at the "just figure stuff out myself" phase. I had a lot of programming experience when I picked up Unity.

atomic sierra
silk night
#

not copy, but recreate, in your own ways

swift crag
#

the goal is to not copy it, but to instead implement the ideas

atomic sierra
#

that makes sense

long matrix
#

Guys i have a question how to make my jump on 2d video game look better? this is my jump velocity code rb.velocity = Vector2.up * jumpSpeed;

atomic sierra
#

but im learning how to make a tower defense game from the very basics

#

like ive never implemented this stuff before

polar acorn
swift crag
#

Separation between learning and doing (or between learning and learning again) is very helpful

#

I often struggle with a problems for a while, then come back the next day and immediately solve it

#

(without thinking about it much in the interim)

long matrix
#

rb.velocity = Vector2.up * jumpSpeed; guys what can i add to make jump more smooth give ideas pls

swift crag
long matrix
#

But someone else solving his problem there

honest vault
violet token
long matrix
#

wdym?

violet token
#
Vector3 velocity;

velocity = rb.velocity;

float ySpeed = Gravity/Jump();

velocity.y = ySpeed

rb.velocity = velocity;
long matrix
#

I dont understand the float ySpeed

violet token
#

For gravity

ySpeed += Physics.gravity.y * Time.deltaTime;

When Jumping

if (Jump())
    ySpeed = jumpHeight;
long matrix
#

Ill give you my jump code

#

!code

eternal falconBOT
dapper forge
#

Hey what can I do when my code doesnt detect my LobbyManager anymore ? He says he is not here anymore

long matrix
#

Gonz

long matrix
#

i get input in update

#

and on fixedupdate do velocity

violet token
#

the ySpeed is a float that each frame gravity will be added pushing your rb down, when you jump, the ySpeed is now the jumpHeight which you character will gracefully jump up and next frame the gravity will begin to pull back down

dapper forge
#

@languid spire No the script has problems too. I doesnt autofill anymore ..

#

I cant even enter Debug.Log or something

long matrix
#

Gonz this will let me jump higher as long as i press more time?

#

or just make the jump smoother

dapper forge
#

it is only on this script

#

it only works not anymore on my LobbyManager Script

violet token
long matrix
#

How i do it in my code? if i get input with bool and not bool function

violet token
#

In your code you are overriding the x and z variables of rb.velocity so even if you can jump it will affect your movement

long matrix
#

Its 2d game

#

when i jump i dont want to move on x

violet token
#

I will share myt code, onlly difference is I use Character Controller not rigidbody

full sparrow
violet token
long matrix
#

ok

silk night
eternal falconBOT
obtuse axle
violet token
obtuse axle
#

When i build my game, and i run the game once, there's no problem. But when i log a second time with another window of the game, when im in one window, i control the second character, and when im in the other window, i control the first character

#

is there a way to switch that?

obtuse axle
#

mb

violet token
obtuse axle
#

yeah but idrk how to fix that

frail star
#

Anyone know how I can fix TMP_InputField? The first time I tap it the android keyboard opens , if I then click outside the keyboard to close it , then tap TMP_InputField again the keyboard doesn't open

violet token
#

maybe implement code to detect on touch input to trigger event that will pull up keyboard

long matrix
#

Gonz i dont understand what does it do?

frail star
#

It opens the keyboard about 40 to 50 percent of the time

violet token
# long matrix Gonz i dont understand what does it do?

This is the best I can do to help you understand lol, its been fun, goodluck

public class Move2D : MonoBehaviour
{
    Rigidbody2D rb;
    Vector2 velocity;

    int speed = 2, jump = 3;
    float ySpeed;

    private void Awake() => rb = GetComponent<Rigidbody2D>();

    // Update is called once per frame
    void Update()
    {
        velocity.x = PlayerInput();  //Stores Input Value (Left/Right Movement)
        
        Gravity();  //Applies Gravity | Handle Jumping

        rb.velocity = velocity;  //Applies Player Movement, Gravity, and Jump to RigidBody
    }

    public float PlayerInput()
    {
        float input = Input.GetAxis("Horizontal");  //Raw Input Value

        return input * speed;  //Product is Movement Speed in Left/Right Direction
    }
    public bool PlayerJump()
    {
        if (Input.GetKeyDown(KeyCode.Space))  //If Jump Button Pressed, Then Jump
            return true;

        return false;
    }
    public void Gravity()
    {
        ySpeed += Physics.gravity.y * Time.deltaTime;  //Stores Gravity to be Applied
        if (onGround())  //Checks if player is grounded to continue
        {
            if (PlayerJump())  //If player is jumping
                ySpeed = jump;  //Override Gravity with jump height

            if (ySpeed <= 0) ySpeed = -.25f;  //If not jumping and player is grounded, Stop applying gravity
        }
        velocity.y = ySpeed;  //Store current direction of travel on y axis
    }
    public bool onGround()
    {
        Ray ray = new Ray(rb.transform.position, Vector3.down);
        Debug.DrawRay(ray.origin, ray.direction * .02f, Color.blue);

        if (Physics.Raycast(ray, .02f))
            return true;

        return false;
    }
}
violet token
drifting atlas
#

how do i cap a value in unity?
if(Input.GetKeyDown(KeyCode.Space) == true) { transform.Rotate(Vector3.fwd * 25); }
I have this to make the character rotate up but I want it to cap at 25

stoic glen
#

How can I change the Pivot of an Object to the bottom of it?

steep mist
#

I’ve been informed that the only way to use unity’s Lobby feature is to code it. There’s a few example codes but none of them have any kind of UI or game object lines.

Can someone walk me through what exactly i need to do to create a lobby

stoic glen
summer stump
# stoic glen 3d

you either make a parent empty gameobject and use that as the pivot, or change the pivot from your modeling software (like blender)

wintry quarry
rancid tinsel
verbal dome
eternal falconBOT
rancid tinsel
#

I did

sand veldt
#

Hi guys is there a way to get a random poin on nav mesh from script

rancid tinsel
sand veldt
#

so i can make the movment of npc random

verbal dome
rancid tinsel
twilit pilot
verbal dome
rancid tinsel
#

I'm not sure what I might have done wrong since it's my first time using the input system

verbal dome
#

Idk about the input system but you are missing a reference

#

The object that has ControlsScript, does it also have a PlayerInput?

rancid tinsel
#

im an idiot

#

is there a way to check through the hierarchy if any other object holds the script

#

oh wait nvm i found it

rancid tinsel
verbal dome
#

For next time

rancid tinsel
violet token
rancid tinsel
violet token
#

Oh I didnt see that haha, it usually are the little things šŸ˜‚

#

Does anyone know why my Raycast detects the terrain but the same ray in a SphereCast does not?

#
    public static bool onGround()
    {
        Ray ray = new Ray(controller.transform.position, Vector3.down);
        Debug.DrawRay(ray.origin, ray.direction * .02f, Color.blue);

        if (Physics.SphereCast(ray, .15f, .02f))
            return true;

        return false;
    }
#

Raycast is the same just without the 2nd param and it works fine

rich adder
timber tide
#

something something spherecast doesn't detect if it's spawned inside of the source

#

overlap does

swift crag
#

Correct.

#

you can combine OverlapSphere with SphereCast to cover your bases

violet token
muted trout
#

i have a rhythm game but the beat of the game becomes unsynced with the beat of the music whenever someone tabs out and tabs back in, how would i fix that?

timber tide
#

maybe try just replaying it at the time in which you tabbed out? I think I've seen someone with this issue before

rancid tinsel
#

how do you reference an input action map in code?

#

as in, set an InputActionMap variable to a specific InputActionMap

wintry quarry
#

Or by name in the generated C# class

rancid tinsel
#

thank you

swift crag
#

praying for InputActionMapReference

#

(there's an InputActionReference, but no equivalent class for an action map)

smoky mauve
#

Why isn't carreras showing up in the inspector?

swift crag
#

you named your class Camera

#

so the name "Camera" refers to your class, not Unity's Camera class

#

change the name of your class

#

oh wiat, that's not "Camera"...

#

I read that as "Camera", whoops

smoky mauve
#

np

swift crag
#

Ah, you just have the wrong attribute on the classes.

#

You use [System.Serializiable] to make a class serializable

#

[SerializeField] on a class definition doesn't do anything

smoky mauve
#

ty

rotund egret
#

[Mobile] How do I make it so the last touch isn't registered on a new scene until the last touch is released?

rich adder
rotund egret
#
{


    bool mouse_over = false;
    


    public void OnPointerEnter(PointerEventData eventData)
    {
        mouse_over = true;
        //Debug.Log("Mouse enter");
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        mouse_over = false;
        //Debug.Log("Mouse exit");
    }

    

    void Update()
    {
        
        if (mouse_over && Input.GetKey(KeyCode.Mouse0))
        {
            gameObject.SetActive(false);
        }
        
       
    }



}

Script applied to each squares

#

also had this, it worked but I had to tap the square one by one and not with one continuous tap

{
bool mouse_over = false;
public void OnPointerDown(PointerEventData eventData)
{
mouse_over = true;
//Debug.Log("Mouse enter");
}

public void OnPointerUp(PointerEventData eventData)
{
mouse_over = false;
//Debug.Log("Mouse exit");
}

void Update()
{

if (mouse_over)
{
gameObject.SetActive(false);
}

}
}
rich adder
#

you can use a DDOL type object that goes through all scenes and tracks mouse instead

lilac olive
#

Hey, How can i make a Live Screen Capture that is accessible Unity?
This is to enable screen mirroring in VR onto a mesh

rancid tinsel
#

I'm trying to set up a binding system with the UnityEngine.InputSystem but the Rebind Save Load script isn't actually saving anything. Any idea what I might have done wrong?

misty coral
#

Oh yea I under stand, your saying because I am basically hitting anything that has an Enemy1 tag

rotund egret
rich adder
#

You need control that somehow, like if(isGameReady == false) return

#

or if they are buttons you can set interactable to false or disable the raycast target

#

until user has released key if holding down when scene was switched

#

I would keep track of that inside a script thet checks the event OnActiveSceneChanged from scene manager.
like psuedo : If Scene was switched and user is holding mouse, activate bool that needs a MouseKeyUp to go to false, and without this on false none of the buttons are actived

rancid tinsel
timber tide
# muted trout \replaying what ?

I mean, save as much of the state as possible when tabbing out then reinstantiate it from that point if possible. (Consider forcing your game to pause too when tabbing which will make the transition less spontaneous)

violet token
violet token
rich adder
#

just overcomplicates what they need

violet token
#

just one more script and can be used for other constants or persistent data

queen adder
raw kindle
#

How can I glue two object together so they move as if they are one objects but still have seperate colliders?

rich adder
#

also adb.exe: error: no devices/emulators found

raw kindle
queen adder
#

maybe the computer doesnt recognize my phone

rich adder
#

it just does smiliar thing

raw kindle
#

for example in my game I have a core (blue) with other objects glued on it, I dont want the object glued to it to clip through walls

rich adder
queen adder
#

i'd make an empty object and put all of these guys inside of it

rich adder
#

check if position is free to move there

swift crag
#

if so, then yeah, just parenting objects together could be a solution

raw kindle
swift crag
#

I know that rigidbodies aren't a huge fan of being parented to each other, but I don't know enough to say if that'll really screw up your game (and this is 2D, where i'm also less experienced)

timber tide
rich adder
#

if they're rigidbodies you can use RbCast in your favor

raw kindle
violet token
timber tide
#

ah, ok, well what you can do then is make an empty gameobject and then parent the cubes that move together. Oh, you'd want to transfer the RB to the parent and probably remove them from the children

misty coral
#

does this have to do with the ambiguous reference

timber tide
#

rbCast sounds good too

crisp anvil
#

any reason why a singleton reference would work in one script but not another?

swift crag
# misty coral

this finds something tagged Enemy1 and tries to get an EnemyCode component from it

misty coral
#

so because its so vague it wont be able to pick out specific enemies?

rich adder
misty coral
#

like I have 3 enemies

rich adder
#

ie accessing before its assigned

misty coral
#

but I have to kill each one in a specific order and if I dont the others dont recieve any damage

timber tide
#

don't use Find then

rotund egret
# violet token What script do you use to switch levels?
        if (AreAllGameObjectsDisabled())
        {
            indexList.RemoveAt(indexList.Count - 1);


            if (AreListsEqual(indexList, compareIndexList))
            {
                
                score += 2;
            }
            else
            {
                score += 1;
            }
            
            timeLeft = deathTimer;


            Debug.Log("GG");

            SceneManager.LoadScene("Main");
        }```

That's just one part of it (in update)
violet token
misty coral
#

i was thinking of trying to identify the enemy by it being hit by a raycast, could that work?

violet token
#

Yes, although you may need a way of storing/accessing that data.

when your raycast hits a target you can pull the id and compare it to a list of bools to see if that target can be damaged

#

say you have an array of 3 bools [0, 1, 2] (false, false, false).

each target will have an id [0, 1, 2]
when the raycast hits a target with id 2, you will check if target 0 and 1 are dead (true), if so, deal damage.

swift crag
#

When you hit something, you get the collider that the ray hit.

#

You can use TryGetComponent to look for a component on the same object as the collider.

#
if (hit.collider.TryGetComponent(out Hurtbox hurtbox)) {
  hurtbox.Damage(12345);
}
delicate portal
#

!collab

eternal falconBOT
misty coral
#

Oh I got it i think

short hazel
swift crag
#

TryGetComponent is really handy

#
if (!hit.collider.TryGetComponent(out Thingy thingy))
  return;

thingy.florp = 123;
short hazel
#

Anything that has this "TryX" pattern is handy

swift crag
#

I've written functions that do several of them in a row and bail out early if any of them fails

queen adder
#

can i set this "0" to be other value via script?

rocky canyon
#

why not just call the function from the other script and pass in 0?

queen adder
#

and how to do this?

rocky canyon
#

thats more for fixed values per the inspector..

queen adder
#

how to check if button was pressed via script

short hazel
#

That is, what they want

rocky canyon
#

referencedScript.MyFunction(value);

short hazel
#

Via the event, ev.Invoke(0) - you'll have to change the event's type to a UnityEvent<int>

rocky canyon
#

ahh events

short hazel
#

Or UnityEvent<float> if you need to pass floats

#

Then, you'll be able to select a function from the "Dynamic int / float" menu of the event's Inspector

swift crag
#

you'll need to write some code

violet token
# misty coral Oh I got it i think
        bool[] defeated = { false, false, false };

        if (Physics.Raycast(ray, out hit, 100f))
        {
            enemy = hit.collider.TryGetComponent<EnemyCode>():
            if (enemy == null) return;

            switch (enemy.id)
            {
                case 0:
                    //Deal Damage
                    break;

                case 1:
                    if (defeated[0])
                        //Deal Damage
                    break;

                case 2:
                    if (defeated[0] && defeated[1])
                        //Deal Damage
                        break;
            }
        }
swift crag
#

the code will respond to the button being clicked by invoking another UnityEvent

#

it'll pass the current number to that UnityEvent

#
[SerializeField] UnityEvent<float> myEvent;

public void DoTheThing() {
  myEvent.Invoke(currentCost);
}
misty coral
#

Ok, thanks!

short hazel
#

And yeah that usage of TryGetComponent is a compiler error here

#

It does not work like that

leaden crow
#

Need a little help here
I'm trying to convert the game I made in school from the old Input Manager to the new Input System and I was wondering, is it possible to call a function with arguments through it?
I'm getting a cannot implicitly convert type 'void' to 'System.Action'

violet token
short hazel
leaden crow
#

Ah I think I have actually done that already I just forgot

#

Oh right I did it to call a Coroutine

#

Is there an actual technical reason why arguments aren't supported in here or is it quirky Unity business

short hazel
#

The syntax you had said "execute this function, then add its result to the event"

leaden crow
#

btw i just realized there's a channel for the input system
I'll make sure to ask there next time

short hazel
#

So yep you need a way to pass a function without actually executing it, and that's done either with what you have now, or with a lambda expression: += () => BuyAmmo(activeSlot) which is an anonymous, inline function

leaden crow
#

I see

#

thanks

short hazel
#

Note that you're not able to unsubscibe from lambda expressions with -=.

eager elm
leaden crow
#

Yeah that one didn't actually need it

#

Unsure of why I bothered adding it rn

#

May be residual code from when I was coding that part since I tried a bunch of different things

wintry quarry
# misty coral

There's no reason to do this.. Again, you would get the reference directly from the RaycastHit. There's no need for FindWithTag and indeed it will give you the wrong result

scarlet skiff
#

Why does my Bomb (https://gdl.space/wuhefuyixu.cs) ALWAYS spawn parryable (https://gdl.space/susonacuke.cpp) bombs if the main bomb was parryable? that should the RNG decide, but when i remove the component it should then never even become parryable (but it still turns red).

And you can see in the message i replied to that the componenet parryable does get removed so how come it still turns red

lilac olive
#

is there a way to script the Rotation of a texture>/

eager elm
scarlet skiff
#

also if the main bomb wasnt red the split bombs wont be red

#

ever

#

100% based on the before-split bomb, which idk how that makes sense

polar acorn
#

If the object was parryable when the component is destroyed it won't turn back to its normal color. Probably instead of destroying the parryable component or not you should set a boolean in that class and use that bool to determine parryability instead of the presence or absence of a component. This way you always have a component that can control the material even if it becomes unparryable

naive tapir
#

It is saying I have nothing attached but I do

NullReferenceException: Object reference not set to an instance of an object
TriggerZoneScript.Update () (at Assets/Scripts/RobotDamageTrading.cs:37)

#

is this a code issue

#

or a variable issue

swift crag
#

Perhaps another instance of the component doesn't have anything assigned

#

You can search the hierarchy for t:RobotDamageTrading to find all instances of the component.

naive tapir
#

thx

covert sinew
#

OnDrag is called for every frame that the pointer is being moved while held down, right?

dusk minnow
#

I have a Problem, i got a player obj(cube) and the colliders of it are attached to it. Rb is in player and the colliders in the attached ones. The script in the attached colliders dont trigger OnCollisionEnter tho?

swift crag
#

Collision messages only get sent to the object with the Rigidbody on it.

#

unlike trigger messages, which go to both the collider's object and the rigidbody's object

#

If you need to know which collider caused a collision, the Collision object has that in otherCollider

#

(somewhat confusingly named; collider is the incoming collider, and thus otherCollider is your collider!

dusk minnow
#

but one collider should detect left collision and one upper collision

swift crag
scarlet skiff
swift crag
#

the examples include code that gets the collision contacts

#

ContactPoint includes "thisCollider" and "otherCollider"

dusk minnow
swift crag
#

Yes.

swift crag
#

I dunno which will be which

#

You can then run code that depends on which of your colliders was involved

dusk minnow
#

it works

warm condor
#

Hey everyone. Is there any way I could simplify this code. My intention with this code is to add acceleration before coming to max speed. Here is my code:

    accilerate(direction);
    limitMaxRunningSpeed(direction);
}
private void accilerate(int direction){
    if (Input.GetKey(KeyCode.LeftShift) ){
        initialiseAccelirationRunningValues();
        accelerateBeforeRunning(direction);
    }
}
private void initialiseAccelirationRunningValues(){
    if (Input.GetKeyDown(KeyCode.LeftShift)){
        speedDuringRunning = Math.Max(initialHorizontalSpeed, walkingSpeed);
        time = timeItTakesToFinnishAcceliration;
    }
}```
covert sinew
#

In an Abstract Class, is there a way to make it so that its Events retain what is in them, adding the override afterwards, instead of replacing it, when overriding them in its child classes?

wintry quarry
#

E.g.

void SomeFunction() {
  DoMandatoryStuff();
  DoAbstractStuff();
}```
#

DoAbstractStuff would be the abstract method

buoyant knot
#

wdym overriding the event

#

you mean you are struggling with the event keyword with parent vs child? or what?

covert sinew
#
public abstract class Dragger : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{

    public bool isDragging;

    public Vector2 mousePosition;

    public void OnBeginDrag(PointerEventData eventData)
    {
        isDragging = true;
    }

    //When the object this is on is dragged
    public void OnDrag(PointerEventData eventData)
    {
        mousePosition = eventData.position;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        isDragging = false;
    }
}

I'm working on an abstract class for making child classes to handle dragging icons, so this up above would be used for making classes that go on an icon, but I also want to be able to add other stuff to this, and was curious if I simply had to re-add the abstract functionality when overriding the virtual events.

#

So This has functionality in OnBeginDrag, and so would the child, but the child would do extra stuff, rather than just setting isDragging to true, if I made it into a virtual class

wintry quarry
buoyant knot
#

so you mean PointerEventData

#

yeah, you basically want the interface to target a method in your class

#

which can be virtual or abstract

wintry quarry
#

I.e.

mousePosition = eventData.position;
AbstractDrag();```
Inside OnDrag
buoyant knot
#

the child class still implements the interface, because it inherits the whole base class.
Interface is just a guarantee that you will find a specific public function with a given signature

covert sinew
#

Like this?

wintry quarry
#

Yep

covert sinew
#

That makes sense. Thank you very much!

#

I'm struggling hard with implementing mouse behavior, with how obscure it seems to be, but this helps a lot.

wintry quarry
#

I would make them protected not public, but yeah

covert sinew
#

All of them?

wintry quarry
#

You could also pass in the event data parameter

wintry quarry
buoyant knot
#

yes. don’t expose a method that doesn’t need to be

covert sinew
#

Is there a reason for that, or is it just for organizational purposes?

wintry quarry
#

Best practice is to expose as little as possible

#

To prevent unintended access and to make the interface to the class as small as possible

covert sinew
#

Aaaah

#

Gotcha.

buoyant knot
#

theoretically, it would work just the same

#

but you shouldn’t

warm condor
queen adder
#

is there a way to blacken the whole screen via code? Blocking all inputs?

dusk minnow
#

When i have a script detecting a collision, can i check what gameobject caused the oncollisionenter to run?

eager elm
dusk minnow
swift crag
#

if so, yeah, a big image on top of everything will work

languid spire
# dusk minnow how

the collision events supply a Collision parameter which has a gameObject property

dusk minnow
#

collision.gameobject?

languid spire
#

whatever the parameter is named but, yes

dusk minnow
#

i have this setup. Player has rb and script with oncollisionenter. The attached childs "collider..." have the collider. How can i check which one detected the collision

swift crag
#

didn't you say you got this working already?

#

by looking at a ContactPoint?

languid spire
#

why not say that in the first place?

queen adder
#

anyone know how to change this material face color to red via script?

dusk minnow
#

i need to check whether child1 or child2 collider was hit

languid spire
#

yes you do becaue those will give you the collider which will give you the gameObject

swift crag
#

you can store references to the colliders on those two child objects

#

and then check which one of them is equal to the collider from the ContactPoint

#

I'm not sure if you want thisCollider or otherCollider. Log both and see which one is yours.

dusk minnow
#

ok, ill try

#

thanks both of u

meager raptor
#

How to solve this

queen adder
short hazel
languid spire
short hazel
kindred stratus
#
{

    public float speed;

void Update()
    {

    if (Input.GetKey(KeyCode.D))
        {
        transform.Translate(Vector2.right * speed);
        }

    else if (Input.GetKey(KeyCode.A))
        {
        transform.Translate(Vector2.left * speed);
        }

    else if (Input.GetKey(KeyCode.S))
        {
        transform.Translate(Vector2.down * speed);
        }

    else if (Input.GetKey(KeyCode.W))
        {
        transform.Translate(Vector2.up * speed);
        }
    }
}``` how would change this to make it use the right physics things instead of transform.translate (I would watch a tutorial on YouTube but there are no tutorials for 4 directional movement)
timber tide
meager raptor
meager raptor
short hazel
timber tide
#

oh it's a tmpro, yeah should just edit the vertex colors itself

languid spire
meager raptor
summer stump
buoyant knot
summer stump
short hazel
#

Is class Interactable abstract or something? Are you using inheritance here?

rare basin
#

wouldn't it be much easier to use interfaces to interactables?

#

so you can just add IInteractable to the class

short hazel
#

It's weird that the script attached to the object is named IBuilding, that is mostly reserved for interfaces yep
Prefixing the name with "I"

rare basin
#

Building : MonoBehaviour, IInteractable

meager raptor
#

i just want to know where the error is coming from

summer stump
short hazel
#

That says "3 asset references" and I bet at least one of them doesn't have the object dragged into the Inspector

summer stump
#

And the "I" prefix should be reserved for Interfaces as they were saying. That made things very confusing

meager raptor
meager raptor
clever oar
#

how can i save the project to be sharable? I mean save scene, scripts and materials? I tried to share full Unity project folder, but it takes so much time and VR project is big.... Package?

leaden crow
#

I'm having trouble with my camera look script, I'm trying to get it to be clamped between 2 diffferent values, but changing the sensitivity is changing how much the camera can actually rotate and I have no clue why

#

It only works properly if the sensitivity is set to 1

short hazel
swift crag
#

(and xRotation)

#

You're multiply xRotation with the sensitivity to calculate the actual angle

#

So if sensitivity is 10, xRotation can be 19, whilst the actual angle is 190

#

that doesn't make sense

#

xRotation += InputManager.Instance.GetCamY() * sensitivity; would be more reasonable.

swift crag
clever oar
swift crag
#

there's nothing intrinsically "huge" about a VR project

leaden crow
#

I thought it didn't matter when the xrotation got multiplied, good to know it does matter

swift crag
#

and then divided by sensitivity afterwards

short hazel
# clever oar i think its same, but i want to save the necessary files which is needed and the...

The standard Unity gitignore will ignore the Library folder. Make sure you have the correct one: https://github.com/github/gitignore/blob/main/Unity.gitignore
And that it's placed at the project root! (where the Assets folder is, not inside of it or above it)

GitHub

A collection of useful .gitignore templates. Contribute to github/gitignore development by creating an account on GitHub.

swift crag
#

The value you were clamping was only equal to the actual value you used to rotate the camera if sensitivity was 1

#

otherwise, you had two different angles entirely

leaden crow
#

The thing is I was under the impression that multiplying xrotation/yrotation in the Quaternion.Euler wouldn't have an effect on the variable itself

leaden crow
#

gah

clever oar
swift crag
#
float angle = 10;
angle = Mathf.Clamp(angle, -50, 50);
transform.rotation = Quaternion.AngleAxis(angle * 10, Vector3.up);
clever oar
#

everything else Unity recreate by own?

swift crag
#

this gives you a 100 degree rotation

#

it doesn't matter that you clamped angle to between -50 and 50; you just multiplied the dang thing by 10!

leaden crow
#

alright yeah

#

that makes sense

swift crag
#

But yes, Unity creates a bunch of stuff as it imports your assets/packages/etc.

short hazel
nocturne parcel
#

Hey guys, help me understand async/await. SO, I was under the impression it would behave like a Coroutine in some way, allowing the rest of the code to go on without blocking it.
Here, SaveWorld() is an async method (https://pastebin.com/4Q9xX2AH). It uses WriteAsync (I'm not implementing the queue functionality just yet, so ignore it).
So does LoadScene() loads a new scene without waiting for the save file to be written or not?

night swift
#

anyone have a simple rundown on how to make a dual weapon system? (like right click for left gun, left click for right gun)

timber tide
#

there's your input, now fill the gaps with your equip logic

short hazel
covert sinew
#

I have a few questions that I can't easily find answers to.

Does OnDrag fire every frame, or just once, when a mouse is being dragged? Should I make it so drag effects only end on OnPointerUp, if the intent is for a drag to only end once you actually let go, rather than once you stop moving the mouse?

Are the pointer events only called on the object, or, for example, is "OnPointerDown" called whenever you click, on all objects that are listening for it?

#

It's not totally clear if I'm meant to explicitly check which object is being interacted with in the script, using the eventData associated with the event, or if the event itself is only being called from within the object that is being interacted with with the mouse.

nocturne parcel
short hazel
#

No, as you don't await in void CreateNewWorld()

timber tide
#

or explicitly unset it

covert sinew
#

Right, so as long as I set dragging, it will remain until the mouse comes up.

#

Good to know.

nocturne parcel
timber tide
#

OnPointerDown is called from the gameobject with the script

summer stump
short hazel
covert sinew
#

Thank you, Mao. I understand these questions may seem obvious, but I don't like making assumptions in unity, considering sometimes it can be a bit...

timber tide
#

Yea, stuff like BeforeDrag and AfterDrag are one time calls too

#

BeforeDrag -> OnDrag (till release) -> AfterDrag -> OnDrop

nocturne parcel
short hazel
#

Yeah and adding a try/catch won't do anything because there's no visible exception being thrown

nocturne parcel
#

I mean, it does what I wanted: it does not block gameplay while saving.

#

Unless there is a better way to do this

short hazel
#

It's thrown inside the async method which runs "elsewhere", but there's nothing (the await) to "bubble up" the exception to the caller, the task is deemed as faulted and just stops running silently
You can still handle exceptions from inside the async methods though

nocturne parcel
#

I mean, I had an exception still thrown

#

When I tried to save immediately after loading a new scene

#

I got an access violation because I tried saving while still writing the file

#

The exception still ocurred

short hazel
#

Unity somehow caught it because of its internal workings and logged it to the console, but if you put a try/catch in the method where you don't await, the catch will never happen

nocturne parcel
#

I see

#

thanks for the info, very helpful

wispy jetty
#

Ive been working on a little project just for fun and I came across a issue, The sounds play just fine whenever their not set up to swap scenes but whenever they are set up to swap scenes they do not play

lone iris
#

Im working on a rougue like top down shooter without procedural generation, i wrote down some pseudo code for an enemy spawner, is there a better way to do it?

#

Public int enemys_to_spawn
Public int enemys_spawned
Public gameObject Enemy

[timer]
Private float spawnRate
Private float timer

Start
{
Timer = 0f
Enemys_spawned = 0
}

Update
{
If (enemys_spanwed <= enemys_tospawn)
{
If (timer < spawnrate)
{
Timer = timer + time.deltaTime
}
Else
{
Spawn()
Timer = 0
Enemys_spanwed ++
}
}
Else
{
Destroy game object
[or]
Change animation
}
}

Void spawn()
{
Instantiate (enemy, transform.position, transform.rotation)
}

eternal falconBOT
lone iris
silk night
#

still formatting would help

#

And yes, you should look up coroutines and "WaitForSeconds()"

lone iris
silk night
#

you can just have a loop in the coroutine and at the end of the loop use the WaitForSeconds, so you can have an interval between it, maybe have a cancel property too

lone iris
#

Yeah

lilac olive
#

is it possible to screenshot the FULL users screen? like not just the game

silk night
#

you can look for a library for it, compile it into a dll and call that

lilac olive
#

Are C# Dll usable? as its .net

kindred stratus
#
{

    public float speed;
    public Rigidbody2D pRb;

void Update()
    {

    if (Input.GetKey(KeyCode.D))
        {
            pRb.velocity = (Vector2.right * speed);
        }

    else if (Input.GetKey(KeyCode.A))
        {
            pRb.velocity = (Vector2.left * speed);
        }

    else if (Input.GetKey(KeyCode.S))
        {
            pRb.velocity = (Vector2.down * speed);
        }

    else if (Input.GetKey(KeyCode.W))
        {
            pRb.velocity = (Vector2.up * speed);
            print (pRb.velocity);
        }
    }
}``` everytime i press a key it moves me but it keeps going until a hit a diffrent key then it keeps going in that direction. anyone knlw how to fix this?
languid spire
kindred stratus
languid spire
#

no, because you do not tell it to

covert sinew
#

Question, how do I get the screenspace coordinates of a UI element? I'm trying to set an icon's position to match that of the mouse, but because it's a child of other objects, I can't just make its AnchoredPosition match the mouse's screenspace coordinates.

buoyant knot
lilac olive
#

Assembly 'Assets/CaptureScreen.dll' will not be loaded due to errors:
Unable to resolve reference 'System.Drawing.Common'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.

is there a way i can use System.Drawing.Common>

buoyant knot
#

Canvas has a method/property to convert between original canvas space and rescaled canvas space (ie screen space)

kindred stratus
buoyant knot
#

you need BOTH camera and canvas methods to go between UI space and world space

languid spire
minor patio
#

so I have a method on a button that is returning an object I'm searching for twice, and I've got no idea how to debug this - I don't know if it's my code of if it's because I've got the same script attached to multiple buttons...

buoyant knot
covert sinew
buoyant knot
#
  1. Input => input vector
  2. input vector => change velocity
buoyant knot
#

the camera governs screen space

minor patio
buoyant knot
#

UI elements live in canvas space.
Canvas applies resizing (depending on screen resolution) to render onto screen space.

languid spire
buoyant knot
buoyant knot
#

you run into a wall while holding left, the wall takes your velocity, and then you stop pressing left, so now you move right

languid spire
summer stump
buoyant knot
kindred stratus
buoyant knot
#

once you have a simple Vector2 that represents what direction you are ā€œpressingā€/holding/etc. Then you can convert it to an actual velocity

languid spire
buoyant knot
#

you know what he means. Stop going the monkey’s paw approach of technically granting a wish, while giving him something he doesn’t want

minor patio
#

ladies, please - take it outside... XD

swift crag
#

I imagine that's something you want.

quiet scaffold
#

I have a button listener added, but it doesn't activate the OnOptionChosen function when i click any of the 3 buttons


    public void Start()
    {
        Debug.Log("starting method");
        foreach (Button button in upgradeButtons)
        {
            button.onClick.AddListener(OnOptionChosen);
        }
    }


    void OnOptionChosen()
    {
        Debug.Log("Clicked");
        disableUpgradeScreen.SetActive(false);
        Debug.Log("Disable screen");
    }
```and yes, they are assigned
languid spire
minor patio
ionic zephyr
#

if I want to do a melee fist attack is it okay if I create a gameobject with a collider that is child of my player?

#

or is there a better way to do it

minor patio
#

aww, my problem is getting swept under the rug... 😦

surreal wagon
#

can someone please help me here, This is my code for displaying a highscore but when i play the game it doesnt display it

teal viper
summer stump
surreal wagon
summer stump
#

Either use a set property where it updates text
Or set it after the entire if else chain

summer stump
minor patio
summer stump
#

I also recommend against using playerprefs in this way at all honestly
Disk read/write is not something you want to use every frame

minor patio
#

Debug.Log entries

surreal wagon
# summer stump Yes

thank you that worked but when i die and the game resets my high score goes down to 0 again

minor patio
silk night
surreal wagon
summer stump
buoyant knot
#

PlayerPrefs is convenient, but it effectively permanently saves data to your computer even if you uninstall the game

teal viper
buoyant knot
#

JSON is a file format. I am telling you to save a file (in JSON format) with your data. Unity specifically has several tools to convert an object to a JSON file format

minor patio
surreal wagon
buoyant knot
#

you’d need to look it up. Velvary has a youtube video guide on that

minor patio
buoyant knot
teal viper
#

I thought it was called from the button?

#

Share the code that you call the method from

#

And share the button setup. Take a screenshot of it's inspector

minor patio
buoyant knot
surreal wagon
teal viper
teal viper
summer stump
#

It's a logic issue

surreal wagon
#

a what now?

summer stump
#

I assume you reload the scene when you die?

surreal wagon
#

yes

summer stump
teal viper
#

1 + 1 is 2 you know

craggy oxide
#

no

#

3 actually

#

sorry

minor patio
#

but thanks for pointing that out

craggy oxide
#

you're welcome

summer stump
# surreal wagon yes

Then the player is destroyed and a new one is created. So the score variable is reset, to 0.
You would want to read from file rigit then (after the scene loads).
But a better choice, as I said earlier, is to have score held by a manager singleton that is in DontDestroyOnLoad, so you sidestep the issue entirely
Then only load from JSON when you start the game or save

surreal wagon
#

im sorry if thats easy im new to unity

summer stump
#

Whenever you see something you don't know, just google "unity [term]" and the docs will come up

#

There is example code there

ionic zephyr
#

if I am making a 1 vs 1 combat system is it better to make an Overlap Circle or a child collider2D in this case????

minor patio
teal viper
minor patio
silk night
ionic zephyr
#

yeah

silk night
#

Block out your characters with colliders and attach circular triggers to the attacking part (e.g. fist, sword)

ionic zephyr
#

oh sorry, they are humanoid but not as big

teal viper
ionic zephyr
#

this is my reference

silk night
#

oh, do you dont need that exact precision?

ionic zephyr
#

yeah, thats it bro

minor patio
silk night
#

then go for the shape that feels best, i would test a box and a circle

ionic zephyr
#

and should I make it a child of the player?

silk night
#

You can attach it to the parent or make it a child, depending on how complex your character is

#

if you dont catch collision events it propagates up to the parent script

ionic zephyr
#

okay, thanks

mild halo
#

Anyone have any idea why I basically never hit r_strafe in my blend tree? movementX and movementY definitely track accurately, and quickly, and basically every other state I have works perfectly, it's just this one Q.Q

silk night
#

same for l_strafe or does that work better?

mild halo
#

l_strafe works perfectly

#

where it should be going to r_strafe, it seems to default to the first item in the blend tree

silk night
mild halo
#

my b

sullen trail
#

Is this a good description of what is going on in this code? Just trying to properly apply lambda functions to my code

austere monolith
#

!code

eternal falconBOT
austere monolith
sullen trail
# austere monolith !code

Again, not asking for help with my code. Im asking if the description that is going along with the code is accurate to what is going on

austere monolith
sullen trail
#

Gotcha

austere monolith
#

lol

#

im not an expert

sullen trail
#

no worries lol

north kiln
worldly widget
violet topaz
#

How do i hide the text after i pick it up. I tried a bool but i kept giving me a error. code-```cs
public class ObjectGrabbable : MonoBehaviour
{
private Rigidbody objectRigidBody;
private Transform objectGrabPointTransform;
public float smoothTime = 0.3F;
private Vector3 velocity = Vector3.zero;
private void Awake()
{
objectRigidBody = GetComponent<Rigidbody>();
}
public void Grab(Transform objectGrabPointTransform)
{
this.objectGrabPointTransform = objectGrabPointTransform;
objectRigidBody.useGravity = false;
}
public void Drop()
{
this.objectGrabPointTransform = null;
objectRigidBody.useGravity = true;

}
private void FixedUpdate()
{
    if(objectGrabPointTransform != null)
    {
        
        transform.position = Vector3.SmoothDamp(transform.position, objectGrabPointTransform.position, ref velocity, smoothTime);
        objectRigidBody.MovePosition(transform.position);
    }
}

}

#
public class PlayerInteractUI : MonoBehaviour
{
    [SerializeField] private GameObject containerGameObject;
    [SerializeField] private PlayerInteract playerInteract;
    [SerializeField] private TextMeshProUGUI interactTextProUGUI;


    [SerializeField] private Transform playerCameraTransform;
    [SerializeField] private LayerMask pickUpLayerMask;

    private void Update()
    {
        float pickUpDistance = 2f;
        if (playerInteract.GetInteractableObject() != null && (Physics.Raycast(playerCameraTransform.position, playerCameraTransform.forward, out RaycastHit raycastHit, pickUpDistance, pickUpLayerMask)))
        {
            Show(playerInteract.GetInteractableObject());
        }
        else
        {
            hide(); 
        }
    }
    private void Show(IInteractable interactable)
    {

        containerGameObject.SetActive(true);
        interactTextProUGUI.text = interactable.GetInteractText();
    }
    private void hide()
    {
        containerGameObject.SetActive(false);
    }
}
austere monolith
rocky canyon
#

hello fam.. hows the waters today?

rocky canyon
violet token
swift crag
violet token
#

I wouldn't really handle interactions the way he is but it's my best guest llol

#

I would have each interactable GO derive from Interactive then on raycast collision pull interactive and trigger interact prompt

swift crag
#

Yes, the player should be raycasting to look for an interactable object

violet topaz
#

so what should i do?

violet token
#

I would raycast for collider with Grabble (base script). If detected trigger grab prompt.
When grab button pressed invoke method to store current distance from ray origin to grabbable position.
Store Grabbable Transform and update position of Transform in update to x distance along raycast.

Sorry I might now be explaining properly

swift crag
#

you should have one place the does the raycasting. It should look a bit like this:

public Interactable targetedInteractable;

public void CheckForInteractable() {
  targetedInteractable = null;
  bool canInteract = true;
  
  if (holdingObject)
    canInteract = false;

  // you can add other conditions too. maybe you can't
  // interact while jumping, for example
    
  if (canInteract && Physics.Raycast(...)) {
    // assign something to targetedInteractable in here
  }
}

You'd call CheckForInteractable() once per frame before you try to do anything with the targetedInteractable field. If you're allowed to interact and the raycast finds something to interact with, then targetedInteractable will be non-null. Otherwise, it will be null.

#

you could also return an Interactable from CheckForInteractable, I suppose

sour fulcrum
#

More of a C# question I suppose, but if I have a list of ints and another int, what's the best way to figure out which int in the list is closest to my other int?

native seal
#

loop through all while storing a closestvalue then return that at the end

#

updating if there is one closer durign the loop

#

you could also use Linq

sour fulcrum
#

whats the relevant linq function for this kinda thing?

native seal
#

OrderBy

#

then call .FirstOrDefault

#

it is less efficient than a loop though

#

just less lines

sour fulcrum
#

yee in this context performance should be fine

#

ty for the advice

native seal
#

np

violet topaz
#
public class PlayerInteractUI : MonoBehaviour
{
    [SerializeField] private GameObject containerGameObject;
    [SerializeField] private PlayerInteract playerInteract;
    [SerializeField] private TextMeshProUGUI interactTextProUGUI;


    [SerializeField] private Transform playerCameraTransform;
    [SerializeField] private LayerMask pickUpLayerMask;
    ### ADDED ###
    public ObjectGrabbable objectGrabbable;

    
    private void Update()
    {
        float pickUpDistance = 2f;
        if (playerInteract.GetInteractableObject() != null && (Physics.Raycast(playerCameraTransform.position, playerCameraTransform.forward, out RaycastHit raycastHit, pickUpDistance, pickUpLayerMask)) && objectGrabbable.Grabbed == false)
### ADDED^ ###
        {
            Show(playerInteract.GetInteractableObject());
        }
        else
        {
            hide(); 
        }
    }
    private void Show(IInteractable interactable)
    {

        containerGameObject.SetActive(true);
        interactTextProUGUI.text = interactable.GetInteractText();
    }
    private void hide()
    {
        containerGameObject.SetActive(false);
    }
}
#
public class ObjectGrabbable : MonoBehaviour
{
    private Rigidbody objectRigidBody;
    private Transform objectGrabPointTransform;
    public float smoothTime = 0.3F;
    private Vector3 velocity = Vector3.zero;
    ### ADDED ###
    public bool Grabbed;
    private void Awake()
    {
        objectRigidBody = GetComponent<Rigidbody>();
    }
    public void Grab(Transform objectGrabPointTransform)
    {
        this.objectGrabPointTransform = objectGrabPointTransform;
        objectRigidBody.useGravity = false;
        ### ADDED ###
        Grabbed = true;
    }
    public void Drop()
    {
        this.objectGrabPointTransform = null;
        objectRigidBody.useGravity = true;
        ### ADDED ###
        Grabbed= false;

    }
    private void FixedUpdate()
    {
        if(objectGrabPointTransform != null)
        {
            
            transform.position = Vector3.SmoothDamp(transform.position, objectGrabPointTransform.position, ref velocity, smoothTime);
            objectRigidBody.MovePosition(transform.position);
        }
    }
}```
gaunt crystal
#

Hi I'm having trouble trying to figure out how go fix this error
If anyone would like to help me that would be great I'm very knew to unity coding

frosty hound
gaunt crystal
#

which one do i change the name for?

frosty hound
#

Check your project folder in Unity. Also take screenshots, it's 2024.

gaunt crystal
#

I can't seem to take a screen shot on my desktop for some reason :/ Shift+S+Windows Key don't seem to work but works on other computers

#

I also found my problem Thank you for the help šŸ‘

cobalt creek
#

for non physics ui objects, is rect.contains a good way to detect overlap?

teal viper
cobalt creek
#

thank

teal viper
#

There's Overlaps method for checking overlap with other rect

summer stump
violet topaz
cobalt creek
#
public void printStringList(List<string> list)
        {
            string output = "";
            foreach(string entry in list)
            {
                output = output + entry.ToString() + ";";
            }
            Debug.Log(output);
        }
        
        public void printIntList(List<int> list)
        {
            string output = "";
            foreach(int entry in list)
            {
                output = output + entry.ToString() + ";";
            }
            Debug.Log(output);
        }
``` is there way i can combine these two into one function?
teal viper
#

A generic method

cobalt creek
#

i tries using T but should squigly line

#

oh

#

thank

teal viper
#

You're welcom

fathom gate
#

so i managed to get my scene yiew about a million miles away from my map is there any to like reset its position to (0,0,0) or something

slender nymph
#

not a code question. but you can double click an object in the hierarchy and the camera will move to focus on that object

fathom gate
#

thanks
also my bad im in the wrong channel

lavish magnet
#

How straight forward would it be to make a game launcher? Could i make one in unity? Like multiple games and you click one and it opens? and I want to make the ui clean and have animations

teal viper
lavish magnet
#

Since we dont need an actual entire game engine?

teal viper
#

Yes

lavish magnet
#

Like just code it and use a ui framework

teal viper
#

Yes.

lavish magnet
#

i honestly

#

dont know how to do that

#

Would i be able to use c#

teal viper
#
  1. Select a programming language of choice.
  2. Research what ui frameworks are available for it.
  3. Learn to use the framework.
  4. Write your launcher app.
lavish magnet
#

Sounds good

slender nymph
lavish magnet
#

For funsies!

#

like if theirs 6 games

#

you can just click which and it launches

slender nymph
#

i mean, alright. but like nobody wants to have to download a separate launcher for a game they get through a storefront that already has its own launcher

teal viper
#

How are you planning to distribute the game/s?

lavish magnet
#

These games would just be for personal use

teal viper
#

Okay then.

lavish magnet
#

is that fine or do I have to do it differently

teal viper
#

No. What you have to do doesn't change anyway. You just don't want a steam game to open a launcher suggesting other games to the user(although there are plenty of titles that do that)

lavish magnet
#

might attempt it in unity first

polar wasp
#

yoyo

misty coral
#

using transform.LookAt is bugging my enemy code so they always approach me from the same angle, what can I do?

#

When I try to run in circles they back away from me to try and approach me from a certain angle

polar wasp
#

ermmmmm

#

could i see how it looks in game?

misty coral
#

ok

#

This is before the transform.LookAt is applied:

#

I just want you to get the idea that they can group up at any angle

#

here is what they do with transform.LookAt

polar wasp
#

right

misty coral
polar wasp
#

so even if they surround you separately, they will form into a group?

misty coral
#

They always do this

#

they back up and try to push me to the left side of the screen

#

without transform.LookAt

#

they could group up in anydirection

polar wasp
#

and with it?

misty coral
#

but with it they reorganize whenever i move to specifically get on that side of my character

#

Always like this

#

I dont really know if Im putting it into words well

polar wasp
#

no no i get what you mean

misty coral
#

yea if I try to go on the right side of the screen, they will reposition to push me to the left

#

always

polar wasp
#

maybe you need to use deltas or vectors(?) pretty new to programming as well as that math but from what i know, unless you specify that you want something to move on a delta or vector3, it will move as if it’s running along a graph

#

so it’ll run along the x axis and then down the z in order to get to their target

#

rather than taking the hypotenuse of the shape

#

is my guess, someone may need to correct me

charred spoke
#

What do you want the LookAt to do? Because right now the code seems like a very wrong way to use LookAt

misty coral
#

I just want the enemies to look at the player, so the raycasts I have on them on constantly in the proper orientation

#

Like I already am using one to be able to jump when small ledges are in the way

#

without LookAt the raycasts can end up facing backwards, so it doesn't function as intended

charred spoke
#

Just call LookAt(playerPosition)

eager spindle
#

or MAUI but that's also quite heavy

#

i would honestly use raylib-cs

misty coral
#

like that?

#

now they are just pushing to the right

eager spindle
#

the way you'd do it is that your project folder contains your launcher exe and a folder to your game, so you can call the exe from your launcher

polar wasp
misty coral
#

and they readjust to reach me on the right

#

er

#

ignore the loud ass keyboard lol

polar wasp
#

oh my god

#

i might have been right

#

mwehehehehe

#

i think it is math

misty coral
#

This is without lookAt

#

You can see how they group up on me much more naturally

misty coral
polar wasp
#

and what do you need the raycasts to be straight for?

#

or at least facing the player

misty coral
#

well those lines at the bottem of the enemy objects,

#

I use them to detect when a object is infront

#

so they can jump

#

also

#

if I add an actual model, I want them to be facing the player anyway

misty coral
#

ok

eternal needle
misty coral
#

Like if the enemy turns, the "forward direction" isnt the same as if it looked in a straight direction

eternal needle
misty coral
#

Basically when the enemy rotates, what was considered forward isn't actually the forward direction of the enemy anymore

eternal needle
#

i suggest you just use unity navmesh agents for your AI enemies

misty coral
misty coral
eternal needle
atomic bison
#

good morning there šŸ™‚

#

what is the best approach if i want to instantiate some part of map as a prefab but i need to find the corner of the existin point where should be connected?

#

everytime i try this is instantiate in the middel of the other mesh renderer

#

this is the best i can do

#

the upper piece is the one instantiate but cannot connect the corner

frigid sequoia
#

You can just store it on an empty to do that

languid spire
#

AI Code failing once again

atomic bison
#

yes xDDD

atomic bison
frigid sequoia
atomic bison
atomic bison
#

i cannot understand your example, if i instantiate a prefab with an empty parent, how can i move the content inside without moving the parent?

#

with localposition?

frigid sequoia
atomic bison
#

i really apologize for my english

frigid sequoia
#

Image 1: The big cube is inside of a Empty Parent, the other one is outisde the empty parent, is just a reference so you can see the origin of the empty parent (initially the same as the big cube). You can now, select the cube inside the empty and move it exactly the amount it needs so the origin of the empty aligns with its corner (Image 2); save the empty parent as a prefab and when instatiated it will use the origin of the empty, which is the corner of the actual mesh

#

This makes it way less messy to calculate where you should be instantiating the prefab, if you want to align corners

atomic bison
#

is more easy this way yes

stuck jay
#

How do you show properties in the inspector?

frigid sequoia
stuck jay
#

Mhm

#

[SerializeField] doesn't work

#

Someone told me the only way to show properties is by making private serializable fields

gaunt ice
#

you need field:serializefield

stuck jay
#

Is that the same as SerializeField?

gaunt ice
#

no

#

it tells unity to serialize the backup field

modest dust
#

A property is just sugar syntax for getter/setter methods. SerializeField, as the name suggests, works for fields, not methods. If you want to specify to target the backing field instead, you add field: before your attributes.

frigid sequoia
#

Shouldn't the component name share the name of the attached script???

modest dust
#

Depends on the Unity version

radiant frigate
#

caesar can i have some help in a problem im running into since like 2 hours ago?

#

imma explain it:

#

it may take a while tho

#

i have googled them and couldnt understand what they meant

#

b4 i had an array called probability and then made a list that contained every int inside "probability" but if i added an int to the array it wouldnt transfer to the list and somehow would remember the last version of the array, and the problem solved itself alone

#

i have no clue of how or why this happens

burnt vapor
#

See if the error persists if you remove remainingenemies.Remove(nextEnemyToSpawn);

#

Also a List does not update its position if you remove an index. Perhaps you want a Queue

radiant frigate
#

but then it will just keep spawning it infinitely right?

burnt vapor
#

Sure, but this is a way to check if the error persists

#

It's not a fix

radiant frigate
#

the problem was that, where now is written [SerializeField] public int[] probabilities = { 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 3 };

#

b4 it was written without the 3“s but if i checked the list it wouldnt copy that

burnt vapor
#

Are those weights?

#

Like, probablility of spawning something?

radiant frigate
#

yes

burnt vapor
#

Then you would not even need a list if you have a static length, or I am misunderstanding this

radiant frigate
#

that makes sense

#

but since the engine has a limited amount of money

burnt vapor
#

So if you don't spawn enemies in a queue, maybe instead integrate the weights inside the actual list and contain a struct of weight and the thing to spawn

burnt vapor
#

It's also not the engine but the end user, but a list is not going to make any type of dent you should worry about

radiant frigate
radiant frigate
burnt vapor
#

Sorry I read this as memory

radiant frigate
#

the size of the wave should depend on the money

radiant frigate
burnt vapor
#

I don't think you should write your code around this arbitary limitation though

#

But that's obviously not the issue here

radiant frigate
#

srry if this is spontaneous but can i call you for explaining it completely?

#

its kinda hard to explain on paper

#

if not np

#

i can try to explain it on here

burnt vapor
#

I can't because work

#

But I think your issue is the removal of the reference and because of this you can't manipulate the gameobject

radiant frigate
#

but basically its a system where the engine buys enemies, each one costs certain amount , so whenever it cant afford an enemy it should remove the possibility of even buying it next time it goes through the while loop

radiant frigate
burnt vapor
#

I haven't seen the error before but this seems most reasonable

radiant frigate
#

that error stops to pop up but then it just spawns the first enemy

#

it worked until now

#

i just added the 3“s and another if( enemyType == 3) so the pool is wider

#

i now changed it and wrote it under the instantiate order so it deletes it after

#

idk why it was working earlier tho

#

also remainingenemies is a list, why is there written array.data?

burnt vapor
#

Because a List holds an array internally

#

A List is an array that resizes itself exponentially using new array instances if the old array is too small for what it must contain

#

So if you have a static length you might as well use an array

radiant frigate
burnt vapor
#

The internal array is what Unity uses when you serialize it, I guess

#

So the error is likely Unity not being able to find data anymore in this

radiant frigate
#

so i should just make it public?

burnt vapor
#

No, I still think you remove data and Unity tries to access this

#

Do you happen to have a PropertyDrawer?

radiant frigate
#

i dont even know what that is

maiden parcel
#

hi there, anyone can help me with a unity problem?
i got a school task where a enemy has to follow you and i got that, but the enemy rotates when i freeze the rotation
the code bassicly is that enemi is moving in arround the screen untill it sports the player, but when it spots it, the enemy mades a strange flick
i dont know if its a code problen
but its seems to

#

!code

eternal falconBOT
maiden parcel
keen dew
#

What does a strange flick mean? Can you show a video recording?