#💻┃code-beginner

1 messages · Page 633 of 1

elfin isle
#

huh

polar acorn
#

Make a vector that is your horizontal movement.
Make another vector that is your vertical movement.
Add them both together to make your final movement vector.
Pass that value, multiplied by deltaTime, to controller.Move

#

One of two things is happening then:
A) Something else is setting the values back to white
B) The objects you're looking at in the inspector and the ones getting logged are not the same object.

#

Are you maybe changing the color of a prefab rather than the ones in the scene?

honest haven
#

that function changes the color of the icon(button) but wont for the child

polar acorn
# elfin isle your losing me
  1. Make a vector that is your horizontal movement multiplied by speed
  2. Make a vector that is your vertical movement
  3. Make a vector that is (1) + (2)
  4. Call controller.Move with (3) times deltaTime
polar acorn
honest haven
#

it is a prefab ddol

#

but yes it changes to blue and so should the text

polar acorn
#

Easy way to test, put this line at the end of the coloring section:

Destroy(windowText.gameObject)

If the text still exists, then you're recoloring the wrong object

elfin isle
polar acorn
honest haven
#

thanks

elfin isle
polar acorn
#

You know

#

like what you were already doing

#

Just all in one line so your math was a train wreck

elfin isle
#

im completely lost

#

what are you talking about

polar acorn
#

I am talking about basic addition

elfin isle
#

no not that

polar acorn
#

You have your horizontal movement (in two dimensions because you're on a plane) that is controlled by your horizontal and vertical inputs. You want this value, multiplied by speed.

You have your vertical movement, which is gravity and jumping. You do not want this multiplied by speed

#

So make two variables

elfin isle
#

what

polar acorn
#

I literally cannot explain this any simpler

#

You were literally already doing this

elfin isle
#

no your

#

omfg

#

vertical

#

here is a and d

polar acorn
#

Here, you're doing horizontal and vertical in the same line. Then multiplying it all by speed and deltaTime

elfin isle
#

Z = Vertical
X = Horizontal

polar acorn
#

I'm not talking about inputs

#

I'm talking about world space movement

elfin isle
#

your not??

polar acorn
#

I've explained exactly what I mean by "Horizontal" like ten different ways

#

Please read them

#

Feel free to scroll up I'm not elaborating again

#

Get your sidey-widey movement in one vector.
Get your jumpy-fally movement in another vector.
Add them

#

is that better?

elfin isle
#

oh my god you dont have to be an asshole about it

i thought you were talking about inputs not world space

polar acorn
tacit vigil
#

Hello, I currently have the following

if(Physics.Raycast(ray.transform.position,ray.transform.forward, out hit,Mathf.Infinity,layerMask)){
      hit.collider.gameObject.Face=1;
}

Face is defined in a script of the prefab numFace with a getter/setter

I can guarantee that the raycast will always hit a numFace object, how can I cast the collided gameObject to numFace so Face can be set

eternal needle
#

and setting it equal to 1 would also make no sense

polar acorn
#

You can't cast GameObject to a component, components are not extensions of GameObject, just a type of class that goes on them

elfin isle
polar acorn
tacit vigil
#

ah, ty! I'm so used to standard OOP, i thought monos just like. assimilated into the object or smth. ty for clearing that up

elfin isle
eternal needle
polar acorn
#

GetComponent calls should be avoided when possible, but situations like this fall into the "not possible" category

elfin isle
polar acorn
#

You'll want to actually store the result of (1) plus (2), so you can multiply that result by deltaTime

#

Vector3 is a struct, it doesn't produce any more garbage making a variable of type Vector3 than it does doing the math all in place, so you don't need to cram it all into one line

elfin isle
#

like this?

polar acorn
# elfin isle like this?

Yes, that should fix your issues with the horizontal being too high (now it's getting scaled by deltaTime). You might also need to modify whatever value you have for y since it's smaller than it was before

slender nymph
#

you should also do the speed multiplication separately so that you can normalize horizontal before multiplying by speed (or at least clamp its magnitude) so you diagonal movement isn't faster than other horizontal movement

elfin isle
toxic frigate
#

hello all, does anyone know why my reload code isnt working? it keeps on firing even when its supposedly reloading

void Update()
    {
        if (target != null)
        {
            // Calculate the predicted target position accounting for gravity.
            CalculatePredictedTargetPosition();

            // Rotate turret to aim at the predicted position.
            CalculateRotationToAimPosition();

            // Fire if turret is aimed and not reloading.
            if (!isReloading && Time.time >= nextFireTime && IsAimedAtTarget())
            {
                if (shellsFiredInCurrentMag >= magSize)
                {
                    StartCoroutine(Reload());
                }
                else
                {
                    Fire();
                    shellsFiredInCurrentMag++;
                    nextFireTime = Time.time + fireRate + UnityEngine.Random.Range(-0.1f, 0.5f);
                }
            }

            // If target is out of range, clear it.
            if (Vector3.Distance(transform.position, target.position) > maxRange)
            {
                target = null;
            }
        }
    }
IEnumerator Reload()
    {
        isReloading = true;
        yield return new WaitForSeconds(reloadTime);
        shellsFiredInCurrentMag = 0;
        currentFuzeTime = timeOfFlight + UnityEngine.Random.Range(0.25f, 0);
        nextFireTime = Time.time + fireRate;
        isReloading = false;
    }
polar acorn
polar acorn
elfin isle
polar acorn
elfin isle
polar acorn
#

meaning that absolutely no vertical movement is occurring

elfin isle
sour fulcrum
polar acorn
honest haven
#

i ran it through ai just incase but that cant work it out

mystic ferry
#

Should I
A) Have one script that a bunch of different objects refer to, to change X object in the UI
B) have every script reference the part of the UI they need to change themselves?

sour fulcrum
polar acorn
# elfin isle yuh

If this is everywhere that y is modified, it is not affected by speed

elfin isle
#

should i like restart my unity or smth cause

polar acorn
elfin isle
#

it is very messy

#

but all it does is change the speed

slender nymph
#

at this point you should share the entire class using a bin site so digi doesn't need to keep asking for more and more code as it is revealed that you are doing more and more that could be affecting your issue 👇 !code

eternal falconBOT
mystic ferry
sour fulcrum
elfin isle
sour fulcrum
#

your core logic stuff would just fire off relevant events when stuff changes and your UI Manager would listen and update based on those events

polar acorn
#

But if it got stuck, it wouldn't recompile

sour fulcrum
# mystic ferry Ok thanks.

small example from a project to show what i mean but you probably get it
UIManager.cs

    private void Awake()
    {
        GameManager.OnActiveTurnMovementChanged.AddListener(RefreshMovementUI);
        GameManager.OnNewTurn.AddListener(RefreshTurnCount);
    }

    private void RefreshTurnCount()
    {
        turnCountText.SetText("TURN - #" + GameManager.Instance.TurnCount);
    }


    private void RefreshMovementUI(GameInput newInput)
    {
        string text = "[" + newInput.ToString() + "]";
        if (newInput != GameInput.NONE)
            text = text.Colorize(Color.yellow);

        selectedInputText.SetText(text);
    }
hidden fossil
#

what happens after i installed .NET SDK?

eternal needle
slender nymph
#

also how are you still on this? it's been an entire day

hidden fossil
#

i think my vs code is now configured

hidden fossil
slender nymph
# hidden fossil

yes, now you can open up the other file you had and find all of the usages of that event you were having trouble with

hidden fossil
#

oh wait what the

#

now its fixed?

#

yea it fixed on its own

slender nymph
#

you likely changed something that you don't remember

hidden fossil
#

i just didnt save the work i did last night

slender nymph
#

right so you changed something, you forgot what it was that you changed, and now you've finally saved and compiled your code so that it updated in unity

hidden fossil
#

no i remembered i didnt save what i did last night

#

i did something last night that caused the issue so i just exited without saving and now its fixed

slender nymph
#

if what you had done that caused the issue wasn't saved, then the issue would not have appeared because that change would not have been compiled.

tawny grove
#

i feel like this is a really bad/inefficent way to detect the key being pressed and then detecting when it is released, but i couldnt find a way to do it with the input event systems. any suggestions?

timber tide
#

I wouldnt GetComponent like that and instead store the array/list by the type

polar dust
#

Getting inputs in FixedUpdate is a bad idea, there's a chance that when the user presses the key, that FixedUpdate won't actually call at that exact moment

tawny grove
#

but i couldnt figure out how to pass a bool through the event

eternal needle
eternal needle
#

Which would have to be in update also

polar dust
#

Makes sense though!

tawny grove
#

so like
update{
if(getKeyDown.S){do stuff}
else if (getKeyUp.S{do other stuff}
}?

polar dust
#

In my game, I do input in update to store a throttle/steer float, which then gets used in FixedUpdate to drive my vehicle

eternal needle
eternal needle
polar dust
#

It keeps a nice separation between what the player is doing and what the actual vehicle does

tawny grove
#

ty for the help

timber tide
#
if(Input.GetKey(KeyCode.S))
else if(!platformsAreFalse)```
#

I guess similarly for each frame for when you hold down the input assuming those platforms are only ever set true/false in these scripts. One benefit of the event driven input system is that you can just listen for the toggles.

normal hearth
#

How would I make a boxing camera that works like Fight Night Champion's? I'm trying to make a boxing game and that's the thing that's holding it back from being presentable

mystic ferry
# eternal needle Also this kinda depends on your use case. If you're talking about updating a hea...

After careful consideration and watching this talk https://youtu.be/raQ3iHhE_Kk?si=a53ftMwIXI5-_uG_ I will be learning how to use ScriptableObjects.

Scriptable Objects are an immensely powerful yet often underutilized feature of Unity. Learn how to get the most out of this versatile data structure and build more extensible systems and data patterns. In this talk, Schell Games shares specific examples of how they have used the Scriptable Object for everything from a hierarchical state machine...

▶ Play video
patent hemlock
#

My logic now works the way i want it to but is there any drawbacks to why I shouldn't use a IEnumerator Coroutine inside of another IEnumerator Coroutine?

teal viper
#

Depending on how you have it implemented

tawny grove
#

where should i ask questions about like scene vs play issues with lighting(?) maybe transparency?

patent hemlock
teal viper
timber tide
#

Coroutine sequencing is hard. Sometimes I do feel like I nest too much

tawny grove
#

ty

timber tide
#

Sometimes I feel like update would be better off as a coroutine by default ;p

patent hemlock
teal viper
timber tide
#

Just being able to yield the update execution would be nice instead of creating the coroutine in start

#

not a big deal, but I don't see any disadvantages to giving more control of how you exit the update

teal viper
#

You can return from update if you need to exit it earlier.

timber tide
#

Yeah but for example you've some transitional controller where you're fading from one scene to another. You'll usually have the pause the execution of everything until it's complete, especially your primary event controller.

#

So I'll end up having this sequence of logic deeply nested on top of a single coroutine

teal viper
#

That's the way. State machines could help. Engines usually try to keep their default implementation as simple as possible. If every update on a MonoBehaviour was a coroutine, it would add a lot of overhead that is not even required in most cases.

#

Also by design an Update function/method is intended to be something that updates the object once per frame, ideally fast-fast. Making it a coroutine would basically break that assumption entirely.

vague charm
#

Good evening, I am trying to make the water tiles in the game speed up when the player touches them but they don't seem to be interacting with each other. I can make the player delete when the edges are touched but the water does not do a thing. When the player object speeds up thats me clicking the mouse. I added the composite collider 2d and the waterBoost script to it but nothing. What am I doing wrong? x_x

north scroll
#

Trying to reload a basic scene, how come the existing hierarchy components such as UI get deleted? The only thing that stays is the GameManager, which contains in its script DontDestroyOnLoad(), and I was trying to understand how scene transitioning works. Basically I have an int in my GameManager script that I wanted to see if I reload the scene, it would keep the number, but then everything gets deleted so the GameManager cant reference the UI text GO anymore

vague charm
teal viper
north scroll
#

ye my blind ass just noticed that the hierarchy after the reload gets a "Game" GO drop down that contains everything else. But then the GameManager loses the textmeshpro ref i dragged in its inspector. Im guessing im gonna have to dynamically assign these via script then ?

teal viper
mystic ferry
# cosmic dagger Good call . . .

I just rewrote almost everything in my game to use scriptable objects for certain things and it's taken me all night so I hope it was worth it. 😭

tawny grove
#

why does unity hate it whenever i do anything with prefabs? i have to reload the project or itll just keep running the unity_self error whenever i make a new prefab(most the time)

cosmic dagger
safe root
#

!code

eternal falconBOT
safe root
#

https://paste.ofcode.org/349HZK4P2Mjf8nU4TXuxZhh

I need help creating a EnemySpawner but this spawner is following the player with two points (minSpawn) (maxSpawn) that show the area around the player and it make a flat plane. But the issue I having right now is trying to figure out how to make that while also making sure they don't spawn to close to the player. So no matter where the player move it will spawn in this area

timber tide
#

Can make your life easier by just using a radius

tawny grove
#

is there a way i can find where this error is sourced to? it only happens sometimes, but happens immediately after running (the inconsistency is making it hard to find a source)

timber tide
#

Are you using any custom plugins

#

or making any editor tools

#

Try just giving Unity a reset, otherwise it's probably something related

tawny grove
#

uhh smooth pixel pixel is the only outside plugin

#

wdym editor tools?

#

ill give it a reset

safe root
timber tide
#

the distance of an enemy to spawn would simply be the minRadius

#

well, between the min and max radius

safe root
#

But how would I make it inbetween?

timber tide
#

add the min and max to one of the random methods

#

along with a random direction

safe root
#

Could you give me a expample please?

timber tide
patent hemlock
#

how many dumb questions are allowed in a day? I'm struggling to figure out a way to pass variables from an object to a main controller for all objects of that type. I don't know if i should do inheritance or polymorphism.
ex. Object Controller does thing based off of if it's interacting with Object1, Object2 or Object3.

sour fulcrum
#

Could you provide a bit more context? sounds abit more inheritence pilled but the passing of variables might need more elaboration

patent hemlock
#

!code

eternal falconBOT
patent hemlock
sour fulcrum
#

ah for this you would probably just have like a TreeBehaviour MonoBehaviour script that has those values

#

and have different prefabs for the different types

graceful cradle
#

following a flappy bird tut, but my "pipes" spawn too frequently or close together
is this a scaling issue? considering i stretched the image in unity to be more pipe-like... hlp..

eternal needle
patent hemlock
keen dew
eternal needle
graceful cradle
sullen canyon
#

How to Design a Flexible Skill System Like League of Legends or Turn-Based Gacha Games Without Thousands of Classes?

patent hemlock
eternal needle
# patent hemlock I do appreciate your input. I'm just trying to decide what is best for the proje...

scaling it up isnt really an issue here, but i get what you mean. there is just not that many solutions here without adding more complexity. I think the simplest solution would be disabling visuals and the collider. Another thing you could do is have some sort of respawn manager in each scene as its own object. instead of an object trying to reenable itself, you could tell the respawn manager "activate me in 5 seconds".

eternal needle
patent hemlock
eternal needle
#

oh mightve misunderstood what you were talking about in my deleted msg

#

well glad it works 👍

ripe galleon
#

hi, i´m trying since 1 hour+ to find how to add/activate/diasctivate force on collision with a specific object only with visual scripting, could someone help me?

verbal dome
ripe galleon
#

i fixed it lol

#

why is it impulse tho

#

instead of force in the rigidbody 2d add force

verbal dome
#

Impulse is used for one-shot forces, Force is used for continuous forces that are applied every physics frame

#

For example impulse = jump, force = walking

ripe galleon
#

that´s what i actually wanted to do that it becomes faster and faster but it didn´t work

verbal dome
#

If adding force continuously doesn't accelerate you infinitely, you have drag (linear damping) or friction slowing it down

naive pawn
ripe galleon
#

thanks, i will see : )

fleet venture
fleet venture
#

okay great

fleet venture
polar dust
#

.net isn't backwards compatible afaik, but unity has been using 2.1 for a while so there shouldn't be any problems

fleet venture
#

okay

polar dust
#

Best thing is to try it out

tender gazelle
#

Hi guys. So my character has the same problem as yesterday. It shows he doesn't have ground Check but he can still jump. what should i do?

eternal falconBOT
verbal dome
#

Not sure if that vscode is configured either

naive pawn
#

oh yeah, it isn't

#

!vscode

eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

tender gazelle
#

so what should i do?

#

and i dont really think it has to do with the code because i had the same code as yesterday and it worked just fine

naive pawn
naive pawn
#

it's practically screaming the issue

vestal bobcat
#

!code

eternal falconBOT
vestal bobcat
#
    public class PortalWarpToArena : MonoBehaviour
    {
        public Transform arenaSpawnLocation;

        private void OnTriggerEnter(Collider other) {
            print ("something is touching the portal");
            if (other.CompareTag("Player"))  //Ensure player has touched portal
                {
                print("Player is touching the portal");
                TeleportPlayer(other.transform); //Teleport player to destination
            }   
        }

        private void TeleportPlayer(Transform other) {
            //print("Moving player to destination");
            other.position = arenaSpawnLocation.position; //Move player to destination
        }
    }
}

I've put the destination game object in the right spot in the editor, am I missing something stupid that's stopping this from working?

#

the console is showing both print statements properly, it's definitely seeing the player touch the portal object

keen dew
#

Does the player use the character controller?

vestal bobcat
#

Yeah I'm using Unity's starter third person character controller

keen dew
#

If that's the standard character controller then you have to disable it before teleporting the player and re-enable after because the CC tracks its own position separately

vestal bobcat
#

Interesting, so the character controller is already controlling the player location and is overriding the portal, if I understand you correctly?

keen dew
#

right

naive pawn
vestal bobcat
#

Okay cool, so can I just put in public gameobject for it and reference it, then disable>move player>enable?

#

I'm not at the computer now, walking the dog, didn't expect an answer so quick haha

wintry quarry
#

Not GameObject

vestal bobcat
#

Gotcha, thank you

polar acorn
#

You can also call Physics.SyncTransforms() after doing the teleport instead of enabling/disabling the CC, but that'll recompute every rigidbody and CC in the scene and depending on how many you have and how often you teleport it, you might still want to do the enable/disable thing

raw smelt
#

if u use PhysicalVelocity
I should do it
physicsVelocity.Linear = moveData.speed * direction*deltaTime;
or
physicsVelocity.Linear = moveData.speed

wintry quarry
#

that happens automatically inside the physics simulation when it decides how much to move the object each frame

thorn holly
wintry quarry
thorn holly
#

Whoops

#

I better fix that

cosmic dagger
thorn holly
cosmic dagger
#

It's a physics method; it should be applied in the physics update, which is FixedUpdate . . .

thorn holly
#

Alr

vestal bobcat
#

Now it's just giving me
Assets\Scripts\Gameplay\PortalWarpToArena.cs(9,16): error CS0118: 'CharacterController' is a namespace but is used like a type

using UnityEngine;
#if ENABLE_INPUT_SYSTEM 
using UnityEngine.InputSystem;
#endif

namespace Unity.Template.CompetitiveActionMultiplayer
{
    public class PortalWarpToArena : MonoBehaviour
    {
        public Transform arenaSpawnLocation;
        private CharacterController characterController;

        private void OnTriggerEnter(Collider other) {
            print ("something is touching the portal");
            if (other.CompareTag("Player"))  //Ensure player has touched portal
                {
                print("Player is touching the portal");
                TeleportPlayer(other.transform); //Teleport player to destination
            }   
        }

        private void TeleportPlayer(Transform other) {
            //print("Moving player to destination");
            characterController.enabled = false;
            other.position = arenaSpawnLocation.position; //Move player to destination
            characterController.enabled = true;
        }
    }
}
#

I assumed I'd need to use GetComponent to grab it but it won't even let me past creating the variable

cosmic dagger
wintry quarry
#

Why is your code in this Unity.Template.CompetitiveActionMultiplayer namespace?

vestal bobcat
#

¯_(ツ)_/¯

#

I imported the multiplayer stuff to play with it and even after removing it because it wouldn't let me start in my own scene it left its stink all over my project. I guess I have to start over

#

I have this

vestal bobcat
#

Creating a new project and copying my scene and scripts seems to have worked, the player is teleported when touching the portal surface. However, now the camera isn't following the player.

#

oh the joys of learning

#

Okay I just deleted that unit.template.competitiveactionmultiplayer shit after recreating the entire project and it works now. Thanks for your help.

crystal bridge
#
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI; 

public class ClickToBig : MonoBehaviour, IPointerClickHandler
{
    [SerializeField] private Vector3 _bigScale = new Vector3(20f, 20f, 20f);
    [SerializeField] private Vector3 _smallScale = new Vector3(5f, 5f, 5f);
    [SerializeField] private bool _isBig = false;
    private RectTransform rectTransform;

    
    public Button closeButton;

For some reason I can't drag/drop the close button in the field and clicking the search icon yields no results.

verbal dome
#

You can't drag a scene reference into default references

#

It needs to be a prefab

#

What are you trying to do?

wintry quarry
#

^ This.
In general assets (things in the project window) cannot reference things in scenes (things in the hierarchy window)

crystal bridge
#

Yeah, I saw online that the script needed to be added to the button, but I have to adjust script because the button in-game is doing things that the other object is doing. I think I might know how to fix though.

timber tide
#

I never insert anything into those default reference windows if that means anything to you :p

crystal bridge
#

Ok, so I correctly assigned things and now my intentions are being met. I have an object (Let's call it A) that, when clicked on, it grows big AND a Dialogue box appears that contains a Close Button. When the Close Button is clicked, the box is destroyed and Object A shrinks back down to original size. This is all good.

The issue is that the Close Button itself is also growing when object A grows. I thought the Listener method was supposed to make it so the Button wouldn't do what Object A does, but 'listen' to what it is doing so the button knows what to do when to do it.

#
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;  

public class ClickToBig : MonoBehaviour, IPointerClickHandler
{
    [SerializeField] private Vector3 _bigScale = new Vector3(20f, 20f, 20f);
    [SerializeField] private Vector3 _smallScale = new Vector3(5f, 5f, 5f);
    [SerializeField] private bool _isBig = false;
    private RectTransform rectTransform;

    
    [SerializeField] private Button closeButton;

    private void Start()
    {
        
        if (closeButton != null)
        {
            closeButton.onClick.AddListener(ShrinkObject);
        }
    }

    private void Update()
    {
        rectTransform = GetComponent<RectTransform>();
        rectTransform.SetAsLastSibling();
    }

    public bool IsBig
    {
        get => _isBig;
        set
        {
            _isBig = value;
            if (_isBig)
            {
                transform.localScale = _bigScale;
            }
            else
            {
                transform.localScale = _smallScale;
            }
        }
    }

    public void OnPointerClick(PointerEventData eventData)
    {
       
        if (_isBig)
        {
            return;
        }

        IsBig = !_isBig;
    }

    private void ShrinkObject()
    {
        
        if (_isBig)
        {
            IsBig = false;
        }
    }

    private void OnValidate()
    {
        IsBig = _isBig;
    }

    private void OnDestroy()
    {
        
        if (closeButton != null)
        {
            closeButton.onClick.RemoveListener(ShrinkObject);
        }
    }
}
cloud walrus
rich adder
cloud walrus
cloud walrus
rich adder
#

whats the purpose of the rectTransform thing in update?

#

btw you can just do rectTransform = (RectTransform) transform

#

no need for GetComponent

wintry quarry
crystal bridge
#

Object A and Button are not children of each other

wintry quarry
#

So if the script is on the button, it's the button that will scale

rich adder
#

^
if transform is the button then it will expand

crystal bridge
#

I get that, but how will I assign the button/script relation so that Object A shrink when button pressed? My original reference was when I tried to attached object to the script itself (which we covered you can't do). Currently it is attached to the field of script that is on Object A.

rich adder
#

why can't you do[SerializeField] private Transform objectA

crystal bridge
# rich adder why can't you do`[SerializeField] private Transform objectA`

Well the script is assigned to Object A. I set up the script a bit ago to grow/shrink Object A and then been dealing with making the Dialogue box system. Today I'm trying to add this detail to the script.

Are you saying to create the field for objectA and attach it to the field while script is still on objectA?

crystal bridge
#

The script is. The Dialogue box hierarchy which contains the button is on the same canvas, but not a parent/child with object A

rich adder
#

so the close button a separate thing and NOT child of ObjectA that resizes?

crystal bridge
#

Correct

#

ObjectA has no children at all

rich adder
crystal bridge
#

no

rich adder
crystal bridge
#

The Dialogue script does have a field for the DialogueBox, but that shouldn't change parent/child relations, right?

crystal bridge
#

It exchanges the respective objects/texts with the customized options set for each ```cs

object.using UnityEngine;
using UnityEngine.EventSystems;

public class Dialogue : MonoBehaviour, IPointerClickHandler, IBeginDragHandler
{
public GameObject dialogueBox;
public string dialogueText;
public Texture[] portraitTextures;

public void OnPointerClick(PointerEventData eventData)
{

    SwitchTextAndPics();
}

public void OnBeginDrag(PointerEventData eventData)
{
    SwitchTextAndPics();
}

public void SwitchTextAndPics()
{
    dialogueBox.SetActive(true);

    if (DialogueManager.Instance != null)
    {
        DialogueManager.Instance.DisplayDialogue(dialogueText, portraitTextures);
    }
    else
    {
        Debug.LogError("DialogueManager.Instance is null");
    }
}

}

rich adder
#

yeah doesn't seem to be touching the hierarchy but I have no clue what DisplayDialogue is doing

crystal bridge
#

Small note is that ObjectA's script (ClickToBig) does include SetAsLastSibling in the Update to ensure that when it grows, it covers all other objects

rich adder
crystal bridge
#

When playing the game, I confirm that the Photo moves at the very bottom after RhiaDialogueBox

rich adder
#

yeah that shouldn't affect Close Button scale then

#

btw colliders should not be used / needed on canvas objects

crystal bridge
rich adder
#

OnMouseDown is what uses colliders

cerulean hamlet
#

Hello! I'm wrangling unsuccessfully with Unity's runner template. Something in Spawnable is resetting the positions. I disabled snap to grid and added the m_InitialPosition vector, but no luck!

https://paste.ofcode.org/DLfbkzT7N8iW5Bd2BGzPBj

slender nymph
cerulean hamlet
crystal bridge
#

Or maybe even in Awake\

crystal bridge
wintry quarry
#

if you want that to happen conditionally, that's what if statements are for

rich adder
#

if something is changing its size probably want to get to the bottom of it, instead of forcing size with update

rugged beacon
#

why are unity event avoided? or at least all the guides i have seen using event use c# action delegate instead

crystal bridge
rocky canyon
#

bandaid fix's dont last forever

rich adder
wintry quarry
#

if you want to set up the listener in the inspector, that's the way to do it

wintry quarry
rocky canyon
#

set a flag..

rugged beacon
#

i though the same, found it through the code auto completion, but have seen 0 guides using unity events

wintry quarry
#

you are simply growing/shrinking the wrong object

wintry quarry
rocky canyon
#

if u ever used the actions on a button in the inspector you've used unity events

rich adder
rocky canyon
#

someone fact check me.. are those unity events or regular events?

slender nymph
#

those are unity events, UnityEvents are serializable unlike regular c# delegates

rocky canyon
#

ahh, thast a good way to tell

#

thanks 💪 🦅

rich adder
#

I think the more "useless" ones are UnityAction

slender nymph
#

one drawback of a UnityEvent though is that anything with a reference can invoke it unlike a delegate with the event modifier which prevents other objects from invoking it

rocky canyon
#

i have a shrink/grow menu system if it ever loads up

slender nymph
rich adder
#

Ohh okay makes sense.. so they are not just a Unity version of Action

rocky canyon
#

||redacted||

slender nymph
rich adder
slender nymph
#

the name does kind of make it seem like something special though

rich adder
#

Unity prefix makes it sound important lol

rocky canyon
#

lol.. same w/ my project..

#

if u remove SPWN namespace nothings gonna work 😈

rich adder
#

assembly def is next

cerulean hamlet
rocky canyon
#

👀

#

what we lookin for

rich adder
#

another overconvoluted Unity Template

cerulean hamlet
#

Mmmhm

rocky canyon
cerulean hamlet
#

[ExecuteinEditMode] seems pretty risky just from the look of it

#

I don't know why they did that

rich adder
#

it was not good to learn on

rocky canyon
#

beginners need bite-sized chunks

#

not the entire pizzeria

rich adder
#

fr

#

too many abstractions too

cerulean hamlet
#

My gamedev class tossed this into our laps :d

rocky canyon
#

teachers suck

#

"you try it"

rich adder
#

most teachers are failed in the industry for a reason

rocky canyon
#

teachers look for initiative or should...

#

i'd go off the beaten path myself

#

lol

cerulean hamlet
#

I'm on exchange in Ireland for the semester -- having a very different CS experience, course is entirely self-guided and has no AI restrictions. His premise is, just get it done, which doesn't feel conducive to learning imo

rich adder
#

not at all.

#

Unity has actual pathways that teach you from 0

#

these "templates" are meant to be "plug n play" if you feel like going through hours of someone elses thoughts and try to understand why certain things are coded a certain way

rocky canyon
#

unity killed my ram

rich adder
# cerulean hamlet 😭

idk you'd have to check all the abstractions there, like m_LevelDefinition and other externally defined items

frank flare
#

is it possible to initialize it with a custom value?

frank flare
#

ok

sharp bloom
#

Any ideas how should I point a projectile weapon directly to center of the screen/crosshairs?

#

Only things I found was for hitscan weapons

verbal dome
#

Well, you'd need to raycast from the center of the screen and make it look at that point

#

But that would be quite jarring

sharp bloom
#

For now I just simply give the arrow an impulse force forward

verbal dome
#

So you are talking about rotating the projectile, not the weapon?

#

A lot of games actually shoot the projectile from the center of the screen.
You can however have a fake visual object for the projectile that originates from the weapon instead

sharp bloom
#

The projectile is affected by gravity of course but I don't know how to make the aim satisfying

#

Like Hanzo from Overwatch

verbal dome
polar acorn
# sharp bloom Like Hanzo from Overwatch

When it comes to replicating features, you need to really break down what makes up those things. You can't just say "Like hanzo", you need to actually assess what makes it "Hanzo-like"

#

That way you know what you actually want to achieve, and can explain it to people who have good taste in video games and therefore have no idea what that means

verbal dome
#

I really have a pet peeve for when people reference other games but don't even provide a link to said game feature

#

A video or something

#

Can't expect everyone to know every game

sharp bloom
#

I explained it badly

#

What I struggle with is finding the correct rotation for the bow such that the crosshair can be used to aim and lead properly

verbal dome
#

Since the projectile has gravity, the crosshair can't really tell exactly where it will land

sharp bloom
#

Because the arrow is actually physically fired from the bow's position

verbal dome
#

Unless you simulate its trajectory but that would be weird probably

sharp bloom
#

Eventually the player would of course figure out the correct way to aim with some trial and error

#

I have set the forces to be realistic for a crossbow bolt

rare basin
verbal dome
#

You guess wrong

#

Even if I know the character I don't know how the bow shooting looks in game

polar acorn
verbal dome
#

So I'd have to go through the trouble of googling it/looking it up on youtube

rare basin
sharp bloom
#

Yea I just said the first bow aiming game that came to mind, will need to research more of them

frosty hound
#

The issue with not firing directly from the center of the screen is that where the cursor is pointing doesn't let the player know where the projectile will hit, since the distance of the raycast will be different based on how far the thing that you're looking at it.

#

It's the reason why in games like Marvel Rivals, you have to always aim a little to the right to hit things, because the characters stand a little offset and "shoot" from their model positions.

twin bolt
#

Hello, i keep getting this error, from a custom render feature when i try to build my game that says

Did you #if UNITY_EDITOR a section of your serialized properties in any of your scripts?```
 It points towards this script https://hastebin.com/share/gajokizoqi.csharp , and i've tried alot to fix it and nothing works. Does anyone know anything about this?
crystal bridge
#

Looking for Recommendation:

I have a DragDrop script that works great for standard objects. I have other objects which will need to be Dragged&Dropped as well, but the image that you see before clicking will substitute the image.

Looking for insight if I should modify the script I have to apply to both or should I make a different DragDrop script (diff name of course) to use for the image switching methods?

edgy prism
#

Hello, Im trying to have a gameObject bounce off my SolidObjects tilemap I have some code that is somewhat working however I dont think it is detecting hits fast enough. I have tried using OnTriggerEnter2D and OnCollisionEnter2D but neither detect anything, there's gotta be a better way so any advice is appreciated.

void FixedUpdate()
    {
        RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, 1f, tilemapLayer);
        if (hit.collider != null)
        {
            if (hit.collider.gameObject.name == "SolidObjects")
                ReverseVelocity();
        }
    }
wintry quarry
edgy prism
wintry quarry
#

Shouldn't you use the object's actual velocity here?

edgy prism
copper wind
edgy prism
copper wind
edgy prism
copper wind
#

Then use onCollision

edgy prism
rocky canyon
copper wind
#

And also the on collision enter code

edgy prism
#
void OnCollisionEnter2D(Collision2D collision)
    {

        if (((1 << collision.gameObject.layer) & tilemapLayer) != 0)
        {
            ReverseVelocity();
        }
    }
white lagoon
#

my character seemingly doesn't want to get down to the floor, how do i edit the sprite so that the hitbox matches up better

rich adder
white lagoon
#

okay it kinda is though

#

because it's the box collider on his feet that stops it

#

okay maybe still not but it's not related to the sprite

rich adder
#

where is the code part?

rich adder
#

" how do i edit the sprite so that the hitbox matches up better"

white lagoon
#

so how do i make it so the extra box collider doesnt affect the height of the object

rich adder
#

make it a child(actually this one doesn't work if parent has rb) or trigger

white lagoon
#

okay thank you

dense wind
white lagoon
#

one more issue, as u can see the collider is literally in the ground which has the "Ground" tag but the code doesn't activate (it's actiavted when i press w and it doesn't do anything)

dense wind
#

what the heck

white lagoon
#

yes that is a foot collider called groudon

dense wind
#

this code is so cursed im sorry

white lagoon
rich adder
wintry quarry
rich adder
#

and this ^

white lagoon
#

cuz i dont know how to do it correctly

wintry quarry
#

Also why is it a local function inside .. .yeah lmao

copper wind
# edgy prism Sure thing

sorry went afk. Which one is your projectile? it looks like you have a rigidbody on your tilemap gameobject? The projectile needs both a collider and a rigidbody, whereas the thing that is being hit (tilemap) does not need a rigidbody

white lagoon
#

this is code beginner isnt it

wintry quarry
#

OnCollisionEnter2D should be its own separate function, not inside another one, and you don't call it yourself

copper wind
# edgy prism Sure thing

also add a Debug statement in the first line of the OnCollisionEnter2D just to see if it is colliding but the layer mask it setup wrong

dense wind
white lagoon
#

well unity said that OnCollisionEnter2D isn't called

rich adder
rich adder
dense wind
wintry quarry
#

Maybe your IDE said it

#

Unity didn't

#

and if your IDE said that it's most likely not set up properly

white lagoon
#

was as a warning in the console

rich adder
#

probably a UNITY IDE error

wintry quarry
#

but - basically you did something incorrectly

dense wind
#

I think some examples and tutorials would go a long way

#

it would be hard to explain everything you are doing wrong and why

edgy prism
dense wind
#

you seem to just be winging it

copper wind
white lagoon
edgy prism
copper wind
dense wind
#

theres a million examples of how to do what you are doing out there

edgy prism
white lagoon
#

really quite contradictive the advice im getting everywhere

dense wind
#

whats the contradiction

white lagoon
#

people telling me to look at tutorials and other people telling me to not do that

copper wind
dense wind
#

idk whos telling you not to look at tutorials thats just dumb

#

no offense

polar acorn
#

The correct answer is look everywhere

dense wind
#

i dont really think anybody said that

copper wind
#

tutorials are great. relying on them later on isn't but in the beginning you should utilize them

polar acorn
#

You aren't going to find Tutorials that will do exactly what you want, and you should instead try to synthesize from multiple sources

dense wind
#

tutorials will teach you the intuition and skills for how stuff works

polar acorn
#

if it's a good one

#

Don't just look for "How to ___" and copy the code

dense wind
#

dont copy the code, look at the code and try to understand why it does what it says it does

copper wind
white lagoon
#

what the fuckk

#

okay that is my fault nvm

stiff mirage
#

finally made it update a text ui when clicking a button, pretty sure im a pro developer now 😎

dense wind
#

not until you know what you are doing

polar acorn
rich adder
white lagoon
#

note how i realised i did it wrong hence the text under...

dense wind
#

you probably didn't even realize you did use a local function becausr you haven't seen enough code examples to know how code usually works

#

which is why looking for snippets and tutorials online helps so much

#

it builds your intuition

rich adder
#
void Func1(){

//nested func
  void Func2(){
#

only Func1 would be able to call Func2

white lagoon
#

literally the snippet i was given by someone

#

okay nevermind im just tsupid

edgy prism
dense wind
#

but you haven't seen enough full scripts to know where that goes or what it does

rich adder
#

missing basics of c#

edgy prism
#

Do you have any idea what might be missing?

white lagoon
polar acorn
white lagoon
#

collisions aren't native to C# afaik

polar acorn
#

But functions and where to put them are

#

Your issue here had absolutely nothing to do with collisions

white lagoon
#

ye im just misunderstanding if it's a function or not

naive pawn
white lagoon
#

like the problem here is why does the function call for 2 variables which arent separated by a comma ( i know it's a varaible being defined now)

naive pawn
wintry quarry
#

go back to the very basics of C#

slender nymph
white lagoon
#

did u read the whole sentence

naive pawn
#

i don't even understand your message

rich adder
#

thats the TYPE and its name, its 1 thing

naive pawn
wintry quarry
wintry quarry
#

it's not Python

polar acorn
#

There's only one variable there

naive pawn
eternal needle
white lagoon
#

okay so i see 5 people in a row stop their brain functions the second they get to half of the sentence

naive pawn
#

or do you mean the "problem" is in past tense

white lagoon
#

yes that is indeed what is implied by "now"

eternal needle
#

whats the point of even bringing up that example then lol

polar acorn
white lagoon
#

because that was the reason for the problems before

eternal needle
#

thats not related to what your issue was above, which is a basics of c# issue

naive pawn
# white lagoon yes that is indeed what is implied by "now"

and nowhere is it implied in your first sentence. the entirety of your first sentence indicates that it's a current issue

so know that we have clarification of that non-issue, let's move on
do you have any other problems you were gonna ask about

edgy prism
#

Nothing summons people to the chat like a good old fashioned argument

eternal needle
#

avengers assembling everytime a beginner gets a little too confident

naive pawn
#

a hivemind would all reply the same... like yall did lmao

polar acorn
naive pawn
#

they didn't edit that message lmao

#

i don't see any of their messages edited

white lagoon
#

never have i clicked edit in this sever

naive pawn
#

im so confused by this entire interaction....

let's just start a new one

#

anyone got any questions to donate

polar acorn
#

Or adding a second message saying "solved" rather than an edit

naive pawn
#

ok, completely unrelated to the message actually in focus?

#

move on, buddy

edgy prism
#

Im now trying to get the projectile to register a collision in OnCollisionEnter2D but for the life of me it would collide with my tilemap collider

naive pawn
#

detecting hits fast enough
can you elaborate on what you mean by this?
is it phasing through the tilemap or something?

for the collision message, do you have the requirements for that message to trigger?

#

oh wait there are messages after that, one sec

edgy prism
naive pawn
edgy prism
naive pawn
slender nymph
#

if they are using a composite collider for the tilemap (which ideally they would be) then they do need the rb for it, but yeah it should just be static. the actually moving object should have the dynamic rb

edgy prism
#

Ok so seems to actually be colliding now, I cant believe I missed that, I think I tried it by editing the prefab root in my scene then instnatiating a new one. im an idiot but thankyou so much

naive pawn
edgy prism
naive pawn
white lagoon
#

why should isTrigger not be ticked

polar acorn
#

You would get OnTrigger messages

bold iron
#

Hi, im having difficulties figuring interfaces. It seems like the 2 scripts wont link up

wintry quarry
bold iron
#

i was following a tutorial, ill try to rewrite some part thanks for the answer

wintry quarry
#

Presumably

#

Wherever they define Interactor

bold iron
#

ok ill rewatch the video

#

@wintry quarry @polar acorn thanks guys i was blindly following the tutorial and didnt realize it was referencing a script. I got it working

torn night
#

how to get good at coding

#

in unity

rich adder
rich adder
copper wind
# torn night how to get good at coding

practice, but make sure what you are practicing is something you enjoy. If you are practicing boring things you will not only not have fun but not be motivated to learn as much as you would if you enjoyed it

wintry quarry
copper wind
#

if you want to code, you can learn that not with college. college cs is theory and math

wintry quarry
#

False

#

Source I got good at coding by going to school for computer science

copper wind
#

im literally doing my master's degree in CS right now

#

true

#

you learned to code while being at college for CS, separate things

rich adder
#

"AI" can code, learn to be a good engineer / programmer

copper wind
#

if you just want to code, not like advanced design, you can do that without college

wintry quarry
#

It's a good way, that's all I'm saying

snow warren
#

Hi

#

I have a question?

rich adder
#

there might be an answer

teal viper
snow warren
teal viper
#

punctuationthinksmart

snow warren
#

I wanted to ask

Is there any server api that can be used to upload pictures on the server and can be downloaded as well
And do not charge that much

It is because i want my game players to upload pictures as pfps in game

rich adder
teal viper
snow warren
#

For a multiplayer game

rich adder
#

Unity has PlayerData storage you can store the binary data of image

#

or a blob bucket like AWS , Azure etc.

teal viper
#

Might want to research then. It's not like we have a text file with "the best free/cheap services for uploading pictures" on our desktop.

snow warren
snow warren
rich adder
#

if you're going over the limits you might want to better monetize your expenses if you plan such high traffic

sand mesa
teal viper
#

The cheapest would probably be to rent a server and host your own api

sand mesa
#

i accidentally created magnetism

sand mesa
#

and I dont know what to do

rich adder
#

those require you to setup your own APIs like ASP.net

teal viper
sand mesa
#

thats the thing

#

gravity's at 0

snow warren
teal viper
sand mesa
#

and it keeps gravitating to the colliders

rich adder
snow warren
rich adder
sand mesa
#

heres a clearer example

#

this is within the same level as

#

a room where the rules are as follows

#

so wtf

#

oh

#

nvm

#

I found the rpbolem

#

there was a big ass box collider I forgot to reduce

rich adder
#

@snow warren If I were you I'd start with the smaller free tiers with already setup apis for this this way you can use their auth systems, then if you need to scale up go from there.
Its easy to overplan

snow warren
normal mango
#

Hello! I've got a weird technical problem that I feel has a fairly simple solution that I'm just missing. I'm creating a system where players tab an object and the info of that object appears through the canvas, specifically the object's icon and the player's notes. However, I'm having issues where there are multiple objects on screen with the "infoTabActivate" script, and the inputted text isnt saving to the list. i have each object's method as an on-end-edit listener but the console always activates every script at once but still returns nothng. how can i fix this?
https://paste.mod.gg/egckemsxirdb/0

normal mango
#

ah that fixed it, tysm!

normal mango
#

did i call it incorrectly?

#

each object has a specific index value set in inspector

polar acorn
#

Put a log in the function and see if it's ever getting called

normal mango
#

which function?

#

OnMouseDown? im certain it gets called cause the rest of the method works properly

sour fulcrum
#

I know without specifics a proper answer can’t be given but realistically is the cost of creating tuples something I’m ever going to be worried about? (In the context of scales not big enough to justify dots or anything).

Was playing around with how I want to implement certain things and was considering a dict with a tuple as a key. Probably not what i’ll end up doing but got me curious

eternal needle
#

you could profile it but i have a feeling like you'll not see any difference, unless you get to a significant amount of elements, at which point any operation would be slow

polar dust
#

I like making tuples if I'm feeling lazy and want to group a few things together that will always need to be used at the same time later ln

sour fulcrum
#

Possibly but I’m trying to be super generic about it in hopes I can maybe integrate it into my little toolkit package that I use everywhere

eternal needle
#

how would using tuples there be more generic than a class?

#

you can accomplish the same things

polar dust
#

Any more than 3 values and it ends up being easier to make a struct instead, a tuple with 4+ items means theres room for improvement

polar dust
eternal needle
#

not necessarily a struct either

polar dust
#

If I need two values together, there's not much harm in putting them into a tuple

eternal needle
polar dust
#

They're pretty easy to improve later on, there isn't too much complication they bring that'd be difficult to refactor

eternal needle
#

if its written in thinking you'll refactor it later, just write it properly the first time! also this isnt really relevant to what they were actually asking

sour fulcrum
# eternal needle how would using tuples there be more generic than a class?

I might want a central static manager handling this rather than giving the relevant items all the sauce.

The tldr is I want basically a ScriptableStat’s system where eg. An Enemy has a list of ScriptableStat’s (lets say Health, Speed & Damage) and these scriptableobjects are used to retrieve the runtime editable value type value from this central manager by providing the scriptable stat and themselves.

I absolutely could store this kind of stuff on the scriptableobject but just considering potential routes to avoid storing runtime stuff on them if I can. And since I want this to be pretty generic and modular I don’t wanna burden the enemy class too much with all this

polar dust
#

I'm only saying that I like using them for an immediate result, the use case definitely favours a class or struct. Nothing wrong with a lazy solution!

#

I don't think that tuples have too much cost too them

eternal needle
polar dust
#

As far as I know, they're fairly light and cheap

eternal needle
spiral dew
#

I have a Unity project on GitHub using Git LFS.

After making some commits, I reached my storage quota.

What are my options to continue working on the project? Should I buy more storage, clean up old LFS files, or is there another solution?

Also, I'm working on this project with one other person—how does Git LFS work in a small team?

Do both of us need to set it up individually, and how does the storage limit apply to us?

timber tide
#

Can always just stick to placeholder assets then disperse the assets later to the one building the project in chunks

#

audio and textures usually the main culprit and easy enough to substitue till later

umbral bough
#

Hi, I am working on 2 projects that use the same asset that behaves differently(asset is made by me).
In both projects, I wanna extend the partial TrackAsset class.
I included the assemblyref and placed the thing in the correct namespace, however, in one project it works fine and in the other it doesn't.
I have very little experience w assembly def/ref so I would appreciate somebody helping me.

umbral bough
umbral bough
umbral bough
hidden fossil
#

does anyone know why like when i finish this level and it shows the win menu, i click on next level and when i go on the next leve, i start with the amount of money i left off in the last game not 100 like what every game i have starts with

slender nymph
#

show relevant code

hidden fossil
#

!code

eternal falconBOT
slender nymph
#

you can bookmark one (or more) of those sites so you don't need to use the bot command every single time you want to share your code

hidden fossil
slender nymph
#

this object is DDOL which means it is going to stay alive when you switch scenes and keep its current values. Start is also only ever called once during an object's lifetime, so it will not be called on this object again after the first time

hidden fossil
#

oh who do i drag a ddol into a scene?

slender nymph
#

huh?

hidden fossil
#

how do make the levelmanager stay in the scene?

neon forum
#

I split an array and am iterating through it, but I cannot for the life of me figure out what this little trailing blank is at the end. Is it a whitespace? is it NULL? WHat is this?

slender nymph
# hidden fossil how do make the levelmanager stay in the scene?

don't make it DDOL if you don't want it in the DDOL scene. but it simply being in that scene isn't the issue, the issue is that you are expecting a new instance of that object or for it to call Start again, neither of which are possible due to your currnet code

slender nymph
hidden fossil
#

oh is there like a duplicate of the levelmanager causing the levelmanager to stay in DDOL?

slender nymph
#

did you not read your own code or what?

neon forum
# slender nymph are we supposed to just guess what the actual context is or . . .?

I used Json.Split('}') on a json string that I pulled from a json file that was created to hold an array of objects(the array was parsed through and each object serialized).
The Json split mostly worked, but to parse through the string[] created with Json.split I'm using a foreach loop, and I'm finding that there is just a blank(see image), and I don't know what character that is, if any.

slender nymph
#

are you printing an entire string? if so, maybe check if it is null and if not print its length. you haven't shown actual code so naturally i can only guess at what the issue is

neon forum
#

I'm printing each string in the string[] created from splitting one big string, but I'll go with your suggestion because I just want an easy fix

slender nymph
#

that's not going to "fix" whatever the issue is, it's just going to provide more context about what you are printing

neon forum
#

exactly, and then the easy fix will be checking if that string is that context, if so, continue;

slender nymph
#

why are you even parsing this json manually anyway? can you not create an object and just deserialize to that object

neon forum
#

Is that possible with a json list of the same object?

outer coral
#

Is there no way to pass bools by reference to a coroutine? or anything by reference for that matter

neon forum
#

What's really funny is that I finally got it to work, and now I'm most likely going to learn a more efficient, more reliable way to do this entire process

slender nymph
hidden fossil
#

oh is causing the levelmanager to be on dont destroy on load?
private void Awake() {
if (main != null && main != this){
Destroy(gameObject);
}
else{
main = this;
DontDestroyOnLoad(gameObject);
}
}

slender nymph
outer coral
#

rats

hidden fossil
#

problem fixed 👍

#

levelmanager now in the scene no longer in DDOL

slender nymph
neon forum
slender nymph
#

did you create the json manually too? why are you not just using a json library for this?

slender nymph
neon forum
#

no I'm using json.serializeObject for the objects

#

and i couldnt' serialize an array of objects because it breaks

slender nymph
#

that is a limitation of JsonUtility, it does not support collections as the root object, but you can just put the array into some wrapper object and de/serialize that

neon forum
#

ah so that's what they meant, I put the basic object into a wrapper, not the array

#

woops.

sullen dew
#

Can we ask for help in here?

cold mist
sullen dew
#

I'm trying to make a score system and I'm not sure how to go about it.
(I am on Unity Editor with C#, and I'm basically a beginner)

More detail:
I'm making a game that has a similar foundation to Agario in the sense that you eat things and grow in score and size.

I need to make a score system where each food has its own different value, and when eaten, that value is added to a player's score.
What I would want to do is have each instantiated food prefab have a easily assignable score value, and this to be acessed in my food eat script.

I have this right now below where each food is automatically 1 and this is triggered on contact with the food. I want the "1" to be a variable that matches the collided food's value.
playerFoodScore = playerFoodScore + 1;

I want it to be
playerFoodScore = playerFoodScore + collidedFoodValue;

The "food" is 3 different prefabs that are randomly instantiated into the game.

I do not know how to assign this value to each different food prefab and have it detected when my player collides with it. If anyone is willing, could you help me walk me through figuring this out?

#

I can provide more detail or show more detail if needed. I don't think I'm allowed to ask people to join calls on this discord server is that correct? If we are allowed then I can do that gladly.

eternal needle
#

!code for how to paste code in the future

eternal falconBOT
sullen dew
#

That makes sense

fading barn
#

how do i edit the name of all variables with same name in visual studio,

#

for eg i have float speed = 10f; Move(speed);

#

how do i edit the name of variable speed everywhere in the code

#

wait why you deleted

fast relic
#

mixed up vs and vscode

fading barn
#

i had not read the entire thing

#

oh

fast relic
fading barn
#

whats wrong with this code

stiff ocean
fast relic
fading barn
#

no

fast relic
#

or are you just asking for tips on how to make it better

fading barn
#

i am trying to play walk animation while moving

#

it is not playing it

#

stuck on idle

#

so i asked whats wrong

stiff ocean
# fading barn

pretty sure PlayerBody.angularVelocity is the players rotational speed

#

and from the looks of it the player shouldn't be rotating

sullen dew
#

it was easier than I thought it would be I think I was just scratching my head too hard

fading barn
fading barn
stiff ocean
fading barn
#

yes

stiff ocean
stiff ocean
fading barn
#

the problem is with animations

#

here have a look

rich adder
stiff ocean
fading barn
#

its a var though

stiff ocean
rich adder
fading barn
#

i should change it to const cause it is constant

fading barn
rich adder
fading barn
#

am i doing something wrong

fading barn
stiff ocean
rich adder
stiff ocean
#

normally i save stuff like that for after the game's working

fading barn
#

idle has no animation btw

#

yet

rich adder
fading barn
#

ok

rich adder
#

what is the exit condition walk to idle

fading barn
#

shall i debug using visual studios debugger?

rich adder
#

if you want to put a breakpoint that works too

#

do you know how to set it up?

stiff ocean
#

btw nav do you know what's going on here?

#

mv is being set

rich adder
#

what is supposed to do ?

fading barn
#

on console

rich adder
stiff ocean
#

which isn't happening at all

fading barn
#

have i set up animator the wrong way?

fading barn
stiff ocean
rich adder
fading barn
rich adder
rich adder
eternal falconBOT
stiff ocean
#

(the chat script was firing)

rich adder
stiff ocean
rich adder
fading barn
#
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField] private float speed = 100f;
    [SerializeField] Rigidbody PlayerBody;
    [SerializeField] Animator animator;

    void FixedUpdate()
    {
        Movement();
    }

    void Movement()
    {
        PlayerBody.AddForce(transform.up * -Input.GetAxis(InputAxis.Horizontal) * speed * Time.deltaTime);
        PlayerBody.AddForce(transform.right * -Input.GetAxis(InputAxis.Vertical) * speed * Time.deltaTime);

        if(Input.GetAxis(InputAxis.Vertical) < 0f || Input.GetAxis(InputAxis.Vertical) > 0f ||
            Input.GetAxis(InputAxis.Horizontal) < 0f || Input.GetAxis(InputAxis.Horizontal) > 0f ||
            PlayerBody.linearVelocity != Vector3.zero)
        {
            animator.SetBool("isWalking", true);
            Debug.Log("check animations");
        }

        else
        {
            animator.SetBool("isWalking", false);
        }
    }
}
class InputAxis
{
    public static string Horizontal = "Horizontal";
    public static string Vertical = "Vertical";
}
rich adder
fading barn
#

yes

rich adder
stiff ocean
fading barn
#

maybe no\

rich adder
rich adder
fading barn
#

is it ok to set up animations in fixed update?

rich adder
#

I would use update but it should work

fading barn
rich adder
stiff ocean
rich adder
#

seem sketch

stiff ocean
#

ty

fading barn
rich adder
#

thats not correct to do

fading barn
#

ok

rich adder
# fading barn

the animator instance has this controller and you referenced the correct one ?

fading barn
#

leme check

#

you know what

#

let me share the project with you

#

maybe you can see whats wrong

rich adder
#

screenshot should be fine if you show specific thing, there aren't many things that can be wrong

fading barn
#

should i add animator to armature(rig/bones) or mesh?

#

also my avatar field is empty

rich adder
#

if its humanoid and has an armature then it should probably have an avatar

#

without the animations, check if its actually going into the states which seems likely now and probably wrong setup of rig

fading barn
#

can you have a look at my project

#

i will share you

rich adder
#

have the object with that animator selected, drag the animator in a side by side tab game view

fading barn
#

my avatar is empty

rich adder
#

would still check the animator states

fading barn
#

its the animator controller

#

it is not playing animation even without conditions

#

why is this so confusing. isnt unity supposed to be easy

naive pawn
#

"easy" is relative. if it's hard with the given tools, imagine how hard it'd be without any help 🫠
if it's not a code issue, check out #🏃┃animation

fading barn
#

Unreal is easier to setup materials and lighting but runs crap on my laptop and Its way harder to learn

fading barn
fading barn
naive pawn
fading barn
#

Is what I meant

#

And it's done through code so I came here

naive pawn
#

directly or via parameters?

hardy prairie
#

Hi, anyone know to use visual script?

fast relic
hardy prairie
west sonnet
#

I'm following an FPS player controller tutorial using Unity's input system. In the tutorial, the person wrote 'e' in their code, but they don't really explain what it is. I've never seen it before. Does anyone know what it is?

#

I don't think 'e' is a reference to anything either

fast relic
west sonnet
#

Is that not the '=>' ?

fast relic
#

it is the =>

west sonnet
#

So that's the 'e'?

fast relic
#

and e is the parameter

west sonnet
#

Ooh okay

#

Man, Lambda is confusing

#

In the screenshot above, how does the 'e' know what it's referencing?

fast relic
#

because you're adding the method to the performed delegate (i think it's called delegate? not sure on that one) of the action, and it passes in only one argument

west sonnet
#

So would the 'e' reference any of these inputs (W,A,S,D)?

#

When any of them are pressed

fast relic
west sonnet
#

So when I press an input key, e read the Vector2 value which is applied to my input_movement value and then added onto the input character movement value?

fast relic
west sonnet
#

Why is this += then? isn't that adding the input_Movement value back onto the defaultInput.Character.Movement.Performed value (if that's even possible?)?

fast relic
# west sonnet Why is this += then? isn't that adding the input_Movement value back onto the de...

the performed value is a delegate, which is sort of like a set of methods that gets called whenever it's invoked, https://youtu.be/J01z1F-du-E?t=169 (timestamped)

▸ Learn how to CODE in Unity: https://gamedevbeginner.com/how-to-code-in-unity/?utm_source=youtube&utm_medium=description&utm_campaign=events

Learn how to create event-based logic in Unity, using Delegates, Events Actions, Unity Events & Scriptable Objects.

00:00 Intro
00:39 Event-based logic in Unity
01:56 The Observer Pattern
02:49 Delegat...

▶ Play video
verbal dome
#

+= means you subscribe to the action, so that every time the event on the left (...performed) is invoked, the lambda on the right will be invoked too

fast relic
#

it's not adding the value, it's adding the function

brazen pagoda
#

Here's the definition of the performed event:

#

Which shows that any callback that subscribes to this event will receive a CallbackContext. In this particular case a Lambda expression is used and the callback context received here is named e (left side of =>) by the lambda expression for the lambda expression to use in the code it executes (right side of =>)

west sonnet
#

Are lambda expressions used to avoid having to write out entire methods and to keep things compact?

brazen pagoda
#

Yes

#

In Java these constructs are known as "Anonymous functions" because they don't have a defined signature

#

The general idea is "this is the only place you will use this code, so let's skip the many lines of a method"

west sonnet
#

How are delegates/events different from methods?

brazen pagoda
#

Assuming you mean how are "Lambda Expressions" different from method:
Only syntactically, for all intents and purposes

#

There's probably more to it if you dig deep into it

fast relic
brazen pagoda
#

^ Yeah delegates/events are just "a list of methods", but they are variable in the sense that you can add or remove methods from that list when the code/game/app is running without changing the code itself.

scarlet aspen
#

Why do I see complaints from people taking the course on unity learn about beginner scripting among the comments? Isn't that the right approach to learning coding?

brazen pagoda
#

So for example, you might have a system in your combat code that handles damage and health of a character in the game, but you might want to have your UI and Audio systems do things whenever damage is done to a Unity.

In this case I have simplified the delegate so it has no parameters/arguments because here I'm focusing on showing how a delegate/event changes how code is linked.

Imagine the following code:

public class UnitStats
{
    public int Health;

    public void TakeDamage( int damage )
    {
        Health -= damage; // Simplified code for example only

        UIManager.UpdateHealthbar();
        AudioManager.PlayOuch();
    }
}

This is what's referred to as "Hard coupling" with direct hard-coded links between two systems. There are many reasons why you might not want hard coupling. I'll explain that a bit after completing the example of what events are and how to use them:

Another way to "loose couple" the involved systems is by having the combat system post an event and for other systems subscribe to that even if they are interested in it:

public class UnitStats
{
    public event Action OnDamageTaken;

    public int Health;

    public void TakeDamage( int damage )
    {
        Health -= damage; // Simplified code for example only

        OnDamageTaken?.Invoke();
    }
}

For this to affect other systems they have to first subscribe to the event:

public class UIManager
{
    public void Start()
    {
        PlayerCharacter.UnitStats.OnDamageTaken += UpdateHealthBar;
    }

    public void UpdateHealthBar()
    {
        // Healthbar updating code here
    }
}

This essentially does the same thing - well only for the "PlayerCharacter" in this example. But it's more loosely coupled.

west sonnet
#

So e is like the name of a method that isn't being created in the moment that the defaultInput.Player.Movement.Performed is called?

brazen pagoda
#

e would be the name of the first argument that a method would have.
Lambda expressions don't have "names", those are kinda skipped.

fast relic
west sonnet
#
{
    public event Action OnDamageTaken;

    public int Health;

    public void TakeDamage( int damage )
    {
        Health -= damage; // Simplified code for example only

        OnDamageTaken?.Invoke();
    }
}```
west sonnet
#

In the example above

brazen pagoda
#

Events invoke any method that has been subscribed to it earlier

#

So any method that has been added like so: OnDamageTaken += ....

fast relic
#

-# just don't miss the plus

brazen pagoda
#

In this case that would be the UIManager's UpdateHealthbar since that would have been assigned during Start()

#

But assume there would also have been an AudioManager with a similar Start() method to the UIManager in which case both the UIManager and the AudioManager would have methods that would be invoked in that case.

west sonnet
#

To subscribe is += and unsubscribe is -= ?

brazen pagoda
#

Correct

fast relic
#

yea

brazen pagoda
#

And it's always a good habit to make sure "if you subscribe once, make sure to also unsubscribe later"

west sonnet
#

So when you invoke OnDamageTaken, it calls the UpdateHealthBar method. Do you have to put a ? when invoking?

brazen pagoda
#

^ So the ? during invoking is just a good habit because it's the same as doing if(OnDamageTaken != null) first. With events this translates to "check if anyone subscribed yet"

#

If you try invoke an event with no subscribers then you will get an error. The ? avoids that.

west sonnet
#

Lambda expressions only 'exist' when they're being called, right?

#

It's like a method that doesn't exist until it's called

brazen pagoda
#

^ You can think of it that way. It does exist in memory as long as the app is running I think, but for you, the user, you cannot re-use that expression elsewhere.

#

And when I mentioned earlier that these expressions are nameless, i.e. why Java calls them "Anonymous functions" is because without a name you cannot call them. So for that intent they do not exist outside of that delegate.

west sonnet
#

So in this example, the 'name' (or really delegate), is 'e'? and that's what's used to call the lambda expression

brazen pagoda
#

^ I'll convert this to a proper method for you so you can do a direct comparison:

#
defaultInput.Player.Movement.performed += SetInputMovement;

void SetInputMovement(CallbackContext e)
{
    inputMovement = e.ReadValue<Vectro2>();
}

This does the exact same thing as the code you have already

#

So this should answer what e is I hope

#

The main thing lambda expression does here is to skip the naming part SetInputMovement that I came up with for this example. Everything else is the same

west sonnet
#

How does inputMovement affect the value of SetInputMovement?

brazen pagoda
#

The above example is still using an event/delegate but is no longer using a LambdaExpression

#

inputMovement is just some variable in your class somewhere. The code that is executed in both cases is "assign the player's input to the inputMovement variable"

#

SetInputMovement is just a name I came up with for the method/function that I thought would accurately describe what the code inside attempts to do

west sonnet
#

Okay, I think I'm getting it

#

So if you did defaultInput.Player.Movement.performed -= SetInputMovement;

It would stop setting the value of inputMovement, because that method is no longer subscribed to that event

brazen pagoda
#

^ correct

west sonnet
#

I'm not sure I understand why you've put CallbackContext e

#

as an argument

fast relic
#

because that's what the lambda expression has

#

the e is the parameter, it just isn't typed because the compiler can infer the type for lambdas

verbal dome
#

Probably makes more sense if you take a closer look at performed

west sonnet
fast relic
brazen pagoda
#

That is the signature that the performed event is defined with and it's the type of the argument that all subscribers to that event must have to be valid subscribers. If you try to subscribe with a method that doesn't have a CallbackContext parameter you will get an error.

brazen pagoda
west sonnet
#

If you have a method, that you want to be potential subscribers to multiple events, would you have to put multiple signatures?

brazen pagoda
#

^ You would need multiple methods instead, unless all events use the same signature

#

There has to be a perfect match between the event's definition/signature and all methods that try to subscribe to it.

#

You can't have any extra parameters in the method, nor can you have fewer. And the type of the parameters has to match exactly.

limber flower
#

i changed my character model from a capsule to a proper model and now it can jump before it reaches the ground, any ideas?

sour fulcrum
west sonnet
#

Okay, I think I'm getting it. it's super confusing

limber flower
#

nvm i figured it out

west sonnet
limber flower
# west sonnet what was it?

the script i use, uses half the playerheight to figure out when its touching the ground, and apparently i needed to keep the original, smaller playerheight, instead of the new taller one

brazen pagoda
# west sonnet So if you did defaultInput.Player.Movement.performed -= SetInputMovement; It wo...

So a good way to explain how "starting" and "stopping" subscriptions would be useful is by hypothetically extending my HealthBar idea:

Imagine that you only want your UI to show the health of a unit you have selected. If you deselect that unit, or select a different unit, you don't want the healthbar to keep updating when the old unit takes damage.

Example

Here's the old method:

public class UIManager
{
    public void Start()
    {
        PlayerCharacter.UnitStats.OnDamageTaken += UpdateHealthBar;
    }

    public void UpdateHealthBar()
    {
        // Healthbar updating code here
    }
}

Now imagine this instead:

public class UIManager
{
    public void OnUnitSelected( Unit unit )
    {
        unit.UnitStats.OnDamageTaken += UpdateHealthBar;
    }

    public void OnUnitDeSelected( Unit unit )
    {
        unit.UnitStats.OnDamageTaken -= UpdateHealthBar;
    }

    public void UpdateHealthBar()
    {
        // Healthbar updating code here
    }
}

So now instead of subscribing on Start, we subscribe "when the UI is interested in the Unit's damage taken"

This is one of the benefits of Delegates/Events (note that we're not talking about lambdas in this example, just delegates/events).
Delegates are variable - not hardcoded. You can add/remove systems that are "interested" only when that is relevant.

#

And we could make a hypothetical scenario for the AudioManager too - where the AudioManager is more concerned with whether a Unit is within the camera view or not. Perhaps it is subscribed to multiple units at once since there can be multiple units in the camera view. I won't make example code for this, I think you get the idea.

#

Another benefit - and this is why Unity makes you have to learn this now - is that a system using events only needs to be concerned with itself, and does not need to know about other systems that are interested in it.

So basically the UnitStats code does not need to be concerned with UI or Audio. And that is good code design. Similarily, Unity's code should not need to be concerned with your code. It's a one-way relationship. It's your code that is interested in what Unity is doing. It's the UI that is interested in the health change, not the other way around. Imagine if you had to dive into Unity's huge code libraries to add calls to your own methods inside there? That would be horrible. Instead you can just add this neat one-line subscription in your code.

Events allows an external system to get notified when an internal system does something. Another perspective is, you can make a system today that has the ability to communicate with a system made in two years without having to go back and update today's system.

west sonnet
#

Okay, I think I'm getting an idea of it

#

Thank you for all the help!

limber flower
#

im trying to make a script that locks the y rotation of my player model to the y rotation of an object in the scene, but im having trouble figuring out how to write it

#

this is what i have so far

west sonnet
#

Could do object.transform.rotation.y = player.transform.rotation.y ?

#

I think

near wadi
#

reminder for both of you

eternal falconBOT
limber flower
#

oh cool

verbal dome
fast relic
# limber flower

pretty sure you can do transform.eulerAngles.y = object.transform.eulerAngles.y

brazen pagoda
verbal dome
#

That^, except you need to make a separate variable instead of directly modifying it

limber flower
#

do i do public Transform orientation; at the beginning?

brazen pagoda
verbal dome
#
Vector3 euler = transform.eulerAngles.y;
euler.y = object.transform.eulerAngles.y;
transform.eulerAngles.y = euler;```
fast relic
#

yea that

verbal dome
#

Euler angles have some issues like gimbal lock but for most situations like this it shouldn't matter

#

Assuming you have a "traditional" game where world up is always the y axis

limber flower
#

im getting a lot of red squiggles