#💻┃code-beginner

1 messages · Page 713 of 1

polar acorn
#

I don't know, why does the official documentation for CharacterController call .Move twice in one Update?

#

It can work in FixedUpdate, it's literally instant. It doesn't depend on time at all so it doesn't matter which update loop it's in

#

Someone asked about the performance impact of something and you said "If you use FixedUpdate it's fine" when that is not even remotely what FixedUpdate does. Things don't take less processing time because you put them in FixedUpdate

#

It's still going to have exactly as much of an effect on your framerate

frail hawk
#

that sounds better than what you said before

#

but nothing wrong with what i said too, so the whole conversation is actually redundant

polar acorn
polar acorn
naive pawn
low copper
#

I can't figure out how to turn off a light. Starting the scene in pitch black with intensity 0 works. However doing it via code seems to trigger the material / shader (can be viewed in screenshot). Any idea whats going on? How I can truely turn off the light with code?

#
public class LoadingScript : MonoBehaviour
{
    private Light[] lights;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        lights = Object.FindObjectsByType(typeof(Light), FindObjectsSortMode.None) as Light[];
        foreach (Light light in lights)
        {
            light.intensity = 0;
            light.enabled = false;
            Debug.Log(light);
        }
    }
}
grand snow
#

you are only changing the light intensity then disabling the light component, leaving the particles un touched

#

Ah mb the lights are children of the particles

low copper
#

Yeah...thats what I was typing

grand snow
#

so the solution is to SetActive() the main parent

low copper
#

FireParticleSystem?

#

I would prefer to keep the torch + torchholder in the game.

#

Does setActive remove them?

rocky canyon
#

yea, SetActive() will deactivate and activate the gameobject
.enabled = true/false will deactivate and activate the component

grand snow
#

it changes the active state of the gameobject which then affects its components and child objects

#

This is day 1 stuff

rocky canyon
#

may could build the particle system over the torch and then when u disable it u have the placeholder there in place behind it

low copper
#

I knew what setactive did prior

#

Thank you for your help. I will try different approaches

marble orbit
#

hello I need help how could i fix it. It doesnt show the code and I couldnt edit it

safe garnet
#

drag the script from the unity editor to visual studio

rich ice
eternal falconBOT
grand snow
safe garnet
#

sometimes it doesnt work or will open a blank visual studio on slower devices, the drag tends to always work

grand snow
#

miss configuration is the cause, a drag + drop may just open the file as a "miscellaneous file"

strange jackal
#

the following code
interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();

is causing the error
NullReferenceException: Object reference not set to an instance of an object

rough granite
strange jackal
#

I can return the getname to a debug line, so that works... it seems to be the

interaction_text.text part that is failing

#

private void Start()
{
interaction_text = IteractionText.GetComponent<Text>();
}

rough granite
marble orbit
#

whats the wrong on my code the ball should follow my mouse curser but it going to the bottom rigth on my screen and not following

rough granite
strange jackal
#

but the key problem is when I add the .text

rough granite
#

ah i see

#

what variable is the Text?

strange jackal
#

I am trying to update the text in in a text box on a canvas

rough granite
strange jackal
#

the InteractionText game object is a Text box

rough granite
#

it should be "TextMeshProUGUI" as far as i know

marble orbit
rough granite
#

i mean i guess you can but far too many people use it wrong

sour adder
strange jackal
rough granite
eternal falconBOT
rough granite
#

but where you declare it at the top you have to make sure it's the same

strange jackal
#

all good now

marble orbit
#

Heres what i did

low copper
#

I want to enable/disable "Analog Glitch Volume" and "Digital Glitch Volume" and modify their values (intensity, horizontal shake etc) via script. See screenshot below. I can't figure out how to get access to them. But beyond this specific case I'd like to learn how to get access to all values. Is there a trick? I THINK I need to use

[SerializeField] VolumeProfile volumeProfile;

I'm not sure if "Analog Glitch Volume" is a components. I'm not clear how to get their name nor their object variable type? For example I found someone use :

DepthOfField dof;
if (volumeProfile.TryGet<DepthOfField>(out dof)) { depthOfFieldValue = dof; }

But I just don't understand how people know the names/variable types to use. If I can't get them from the inspector is there a list all of them available or something. I would appreciate any help.

dull grail
#

Is there a built-in way to check if pointer over ui element? I saw i could use eventSystem IsPointerOverGameObject but it's page marked as legacy and that in unity 2021 planned to get better way to check it but i can't find anything. My editor version is 2022 so i think there should be some better ways than checking it with raycasts

rough granite
#

if so just this will work

private void OnMouseOver()
{
            
}
dull grail
#

Thank you

wintry quarry
lofty canopy
#
using UnityEngine;

public class MouseManager : MonoBehaviour
{
    [SerializeField] private LayerMask whatIsDesktop;
    [SerializeField] private LayerMask whatIsPlacement;
    [SerializeField] private LayerMask whatIsInteractable;

    private Card selectedCard = null;

    private void Update()
    {
        if (Input.GetMouseButtonDown(0) && !GameManager.Instance.gameEnded && Time.timeScale != 0f)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, Mathf.Infinity, whatIsInteractable))
            {
                if (hit.collider != null && selectedCard == null)
                {
                    selectedCard = hit.transform.GetComponent<Card>();
                }
            }
        }

        if (selectedCard != null)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, Mathf.Infinity, whatIsDesktop))
            {
                selectedCard.MoveToPoint(hit.point + new Vector3(0f, 2f, 0f), Quaternion.identity);
            }
        }
    }
}
#

I'm having trouble with this script.

#

new Vector3(0f, 2f, 0f) specifically this part.

#

cause the gameObject is raised by 2f on the y, it throws off the ratios on the x and z. So as I move closer to the edge of the screen it moves away from the mouse cursor.

#

Anyway to account for this?

#

I realise it's a perspective thing.

sour fulcrum
#

(We don't know what MoveToPoint does)

lofty canopy
#

Card.cs

private Vector3 targetPoint;
private Quaternion targetRot;

private void Update()
{
    transform.position = Vector3.Lerp(transform.position, targetPoint, moveSpeed * Time.deltaTime);
    transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRot, rotateSpeed * Time.deltaTime);
}

public void MoveToPoint(Vector3 pointToMoveTo, Quaternion rotToMatch)
{
    pointToMoveTo = new Vector3(pointToMoveTo.x, pointToMoveTo.y, pointToMoveTo.z);
    targetPoint = pointToMoveTo;
    targetRot = rotToMatch;
}
sour fulcrum
#

by the way, sorry to nitpick but just a quick note that your free to take or leave.

Worth thinking about the priority of your conditionals in situations like this. None of this code will do anything when selectedCard is null so ideally that check should be at the start of the logic, so you avoid needless work. The other conditionals like getmousedown and gameended etc. are doing that kinda thing correctly 😄.

(also good diligence on the null checking but afaik a hit.collider will never be null)

lofty canopy
#

I'm refactoring my code. Moving all the raycast logic which resides in an Update() for Card.cs and just using something called MouseController.cs. I'm basically reversing everything or whatever.

#

So if the selectedCard is null that means I'm not holding a card to place somewhere.

magic imp
#

How do I make something move randomly?

magic imp
#

and he chases you

lofty canopy
#

It just removes the need for private bool isDragging etc.

rich ice
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

rich ice
#

if you've already done that then it should be simple enough using a navmesh and a few pre-defined nodes

magic imp
#

What unity version should I download?

rich ice
#

usually you'd want to pick the latest LTS version

lofty canopy
#

You have two methods of Randomization, both are pseudo-random generation.

#

There's Unity's Random function or C# System.Random.

lofty canopy
# magic imp What unity version should I download?

✅ Get the Ultimate Unity Overview https://cmonkey.co/ultimateunityoverview
👍 Learn how to make BETTER games FASTER by using all the Unity Tools and Features at your disposal!
💬 What is the Best Unity Version? 6.0? 6.1? LTS? Supported? Beta?

💬 Here's how to choose a Unity Version.
The way Unity organizes their versions is actually qui...

▶ Play video
magic imp
#

So the latest LTS is 6.0, time to get that I guess???

lofty canopy
#

If you'll be working on a project for a longtime and want stability, Long Term Support, is generally the way to go.

#

If you want to test out the bleeding edge updates from Unity go with the Tech? version.

magic imp
#

when will it end support?

lofty canopy
#

Just watch the video I posted.

lofty canopy
sour fulcrum
#

Yeah no stress, Just pointed it out in case that was a new insight to you, keep cooking 😄

lofty canopy
#

hit.collider will never be null?

sour fulcrum
#

As far as I know

#

Otherwise it couldn't be hit 😄

lofty canopy
#

cause of the LayerMask?

#

what if I raycast off into the void.

sour fulcrum
#

your using the returned bool off Physics.Raycast

#

that's your null check here

lofty canopy
#

Ah, you are correct! I guess some people can be wrong on the Internet.

sour fulcrum
#

.transform and .collider can be programically null sure, but logically if it's in the context of a conditional raycast they will never be null because there isn't a situation in which the raycast could return positive

lofty canopy
#

That's the only bit of code I was like "Eh, whatever" and chucked it in, not really thinking about it.

sour fulcrum
#

ye its a hyper-nitpick dw

lofty canopy
#

but yeah, how would I go about changing the x and y position ratios the further I move to the edge of the screen?

sour fulcrum
#

For your actual issue, Might need a video? Not quite sure what the issue is and also unsure on what you mean by throwing the x and z ratios off

lofty canopy
#

@sour fulcrum first video is with the new Vector(0f, 2f, 0f) added on to the hit.point.

#

Second video I changed it from 2f to 0f. It's a perspective viewpoint thing. Just wondering if there is an easy way to fix it rather than ratio the x and z positions.

zenith wren
#

how would I go about accessing a bool from another script without having to add a reference every instance?

lofty canopy
#

public bool isThisABoolean { get; private set }

#

make it public?

zenith wren
#

It already is

sour fulcrum
naive pawn
#

if you don't have a reference to an instance, you can't get an instance property since you don't have anywhere to get it from

ivory bobcat
sour fulcrum
naive pawn
#

imagine you have a document with a field on it
if you want to know what the value of that field is, you have to have a document, otherwise the question just doesn't make sense

lofty canopy
#

unless there is only one instance of it running AKA Singleton pattern. You have to search for it, use a [SerializeField], or so forth.

#

and you have to make it a singleton in the script.

lofty canopy
zenith wren
#

basically I'm making an object that will be spawned and needs to be picked up by the player and to make sure the player won't pickup multiple objects I have a bool but every time I try to use it like this it doesn't work when creating a new object

sour fulcrum
#

You want the card to follow your cursor right? Right now you are raycasting from the cursor to the world and making the card follow what you hit. Using the function I linked you can just sample the cursor position converted to screen space directly

#

not 100% sure this is the problem but it might be and will simplify things abit

ivory bobcat
lofty canopy
zenith wren
lofty canopy
#

You can find the player with the Player tag

#

player = GameObject.FindGameObjectWithTag(PLAYER_TAG);

#

and just set a private static String PLAYER_TAG = "Player"

zenith wren
#

in this case the "player" is just the controller script

lofty canopy
#

does the gameobject have the Player tag set on it?

lofty canopy
#

That would work too, and search for PlayerController.

zenith wren
#

yes, or else the cube will teleport to the player anytime it touches anything

lofty canopy
#

Might be better to move the bool check to the player?

#

and if the player is already interacting with a pickup, the other pickups will check this and ignore it. If that's what you're trying to do?

#

You could set the objects Awake method to search for the player variable?

#

or Start, I forget which one.

lofty canopy
#
using UnityEngine;

public class MouseManager : MonoBehaviour
{
    [SerializeField] private LayerMask whatIsDesktop;
    [SerializeField] private LayerMask whatIsPlacement;
    [SerializeField] private LayerMask whatIsInteractable;

    private Card selectedCard = null;

    private void Update()
    {
        if (Input.GetMouseButtonDown(0) && !GameManager.Instance.gameEnded && Time.timeScale != 0f)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, Mathf.Infinity, whatIsInteractable))
            {
                if (hit.collider != null && selectedCard == null)
                {
                    selectedCard = hit.transform.GetComponent<Card>();
                }
            }
        }

        if (selectedCard != null)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, Mathf.Infinity, whatIsDesktop))
            {
                Vector3 newDestination = hit.point + new Vector3(0f, 2f, 0f);
                newDestination.x = newDestination.x * 0.75f;
                newDestination.z = newDestination.z * 0.75f;
                selectedCard.MoveToPoint(newDestination, Quaternion.identity);
            }
        }
    }
}
#

This is what I ended up doing and it worked! 😄

#

Now to not make them magic numbers.

naive pawn
#

uhhh that might be a bit obtuse, huh

#
if (other.TryGetComponent(out player)) {
  isInTrigger = true;
}
#

this would mean having the PlayerController defines the player rather than the tag

west sonnet
#

What's the best way to move the players weapon into an ADS position from hip firing? Would Lerp be good for that?

keen dew
#

Depends what you mean by best and how you want it to work. If you just want it to move between the two positions then yes lerping between them is probably the best. For more control there's the animation curve or tweening libraries

west sonnet
#

When starting the game, my gun moves to a random position and I'm not sure why. I'm trying to set it to my HipFirePosition empty object position. Can anyone help me figure out why it's happening?

halcyon moon
#

hello people,
i have been trying to learn how to make games from my childhood, in elementary school, i learned abit in scratch and developed a 2 player ping pong game then quit programming due to the software requiring a hard learning path for a 10 year old (or i was stupid).

when i was 15 i tried to learn using godot and made a simple platformer game with 4 levels and 2 difficulties but then quit due to the lack of learning media.

from all these time stops i always stopped creating things because i just can't or didn't find a good media to ** actually** learn a language from.

i wanna learn how to make games on unity and like learn the language (c#) it self to properly create and write what i imagine. so will this brackeys playlist do so?
https://www.youtube.com/watch?v=j48LtUkZRjU&list=PLPV2KyIb3jR5QFsefuO2RlAgWEz6EvVi6
if there are any other media that i can learn from i will gladly accept the idea.

Want to make a video game but don't know where to start? This video should help point you in the right direction!

❤️ Donate: https://www.paypal.com/donate/?hosted_button_id=VCMM2PLRRX8GU

·············································································...

▶ Play video
ivory bobcat
west sonnet
ivory bobcat
ivory bobcat
#

So it's whatever value that's being set there that's moving your gun to the unwanted position.

west sonnet
#

But what's weird is that when I press play, the gun doesn't move to the position. You can see where the wanted position is by where the gizmo is, but the gun moves elsewhere

ivory bobcat
keen dew
#

yeah it should be transform.localPosition = ...

frail hawk
keen dew
#

or even better, add empty gameobjects to the positions where you want the gun to move and move the gun to their position instead of setting the positions by hand

west sonnet
west sonnet
keen dew
#

But in the code you have Vector3 variables

west sonnet
west sonnet
#

It's because I wanted to use Lerp to move inbetween hip fire and ADS

keen dew
#

It's not using the empty gameobject's position if you set the position to the Vector3 variable value

#

the Vector3 variable is not the empty gameobject's position

west sonnet
#

Initially, I was just setting the gun position to be one of the 2 empty gameobject position, but it would snap to the position and I want to make it move smoothly. Any ideas on how I could do that?

#

I thought Lerp would work

keen dew
#

That's a different problem

ivory bobcat
#

The gun was placed where you asked it to be placed (dead center relative to it's parent)

west sonnet
keen dew
#

Just naming the variable "HipFirePosition" doesn't mean it has anything to do with the object called "HipFirePosition"

west sonnet
sour fulcrum
#

that would make sense, gameobjects are not vector3's

west sonnet
#

Is there any way for me to assign the gameobject to the vector3? In the inspector, the vector3 are now X,Y,Z values

sour fulcrum
#

no

#

a vector3 is a set of three numbers

#

thats not a gameobject

west sonnet
#

Is it possible to use the transforms of the objects in Lerp?

#

To Lerp the gun from one position to another

keen dew
#

Yes, just the same as with any vector3. They aren't anything special

halcyon moon
frail hawk
#

research. there are many tutorials and documents, create small games like flappy bird , temple run etc

keen dew
#

!learn and there are more links in the pinned messages

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

halcyon moon
#

thanks guys, so it comes naturally while learning other things?

keen dew
#

What is "it"?

halcyon moon
#

the skill and key to the language

#

but yeah the pinned masseges have good guides in them

west sonnet
sour fulcrum
#

Vector3.Lerp takes in vector3's

keen dew
#

Because those are the object transforms, not their positions

west sonnet
#

Ah right, understood

#

Thank you

sour fulcrum
#

if i asked you to stick your toe in the pool and you jumped in the pool

keen dew
#

Also that lerp is way wrong even if you fix the parameters

keen dew
#

If you do (example) position = Lerp(x, y, 1) then it's exactly the same as position = y because lerp goes from 0 to 1 where 0 means all the way to x and 1 means all the way to y

#

It doesn't animate anything by itself

sour fulcrum
#

eg.

Lerp(0, 10, 0.25f) = 2.5f
Lerp(0, 10, 0.5f) = 5
Lerp(0, 10, 10) = 10

keen dew
#

What I suggest instead is make a variable private bool isHipFiring; and then in Update:

if (isHipFiring) {
    transform.position = Vector3.MoveTowards(transform.position, HipFirePosition.position, speed * Time.deltaTime);
else {
    transform.position = Vector3.MoveTowards(transform.position, ADSPosition.position, speed * Time.deltaTime);
}
west sonnet
#

Okay, this is a little confusing to follow. How can Lerp be used to move an object then?

keen dew
#

and on mouse click swap isHipFiring between true and false

sour fulcrum
#

no no it is moving the object, but you have the lerp value at 1 which means its just picking the second value your giving it

keen dew
#

Typically you make a timer from 0 to 1 and use the timer value when lerping

west sonnet
#

So with the lerp value at 1, the object with immediately jump from the first position to the second. Is that right?

sour fulcrum
keen dew
#

but in this case MoveTowards is easier and you don't need to worry about the intricacies

sour fulcrum
#

not even jump, just the second

#

lerp is a little function that you say "hey here's two values and i want the value in-between them based on this value"

west sonnet
naive pawn
#

t says how exactly it's inbetween
0 -> first value
1 -> second value
0.5 -> halfway between
0.25 -> 75% first value, 25% second value
etc

#

so if you want to change the output over time, you change t over time

#

usually by keeping a timer that you add Time.deltaTime to each update

west sonnet
#

Even using MoveTowards, the weapon snaps to the position rather than moving smoothly. What am I doing wrong? transform.position = Vector3.MoveTowards(HipFirePosition.position, ADSPosition.position, 1f * Time.deltaTime);

west sonnet
#

As in "t" represents where the variable should be between the 2 points

sour fulcrum
#

A lerp is commonly used when actually implementing sliders too 😛

west sonnet
# sour fulcrum Yup!

But then why is it that you can use fixed values for the "t" and it still works? For example, this line I found in a tutorial weaponPosition = Vector3.Lerp(weaponPosition, adsPosition.localPosition, aimSpeed * Time.deltaTime);

sour fulcrum
#

what do you mean by "fixed value"

west sonnet
sour fulcrum
#

aimSpeed is a variable. we have no idea if it changes or not

#

but regardless it being fixed or not doesnt really matter

naive pawn
#

that's wronglerp

sour fulcrum
#

the third value is just the slider between the first two values

naive pawn
#

it's basically using the math of lerp to do something that isn't actually lerp

west sonnet
#

Because aimSpeed doesn't change

naive pawn
west sonnet
#

Assuming it doesn't

naive pawn
west sonnet
naive pawn
#

no, weaponPosition itself changes

naive pawn
sour fulcrum
#

its possible you might be overthinking what Lerp does, it's just a little math equation

#

three numbers go in one comes out

#

it does not know nor care about the context behind those values

west sonnet
#

I'm struggling to understand how you determine the speed in which Lerp works. I thought the 3rd value (t) acted as a slider. For example Lerp(1, 10, 2) would be 2. but if the 3rd value never changes, how does the value that lerp is being applied to change?

sour fulcrum
#

Lerp(0,10,2) = 10
Lerp(0,20,2) = 20

(the third value is a slider from 0 to 1 so anything higher than 1 is just treated as 1)

west sonnet
#

Ooooohhh

naive pawn
#

lerp just gets a value in-between 2 other values

west sonnet
#

Lerp(0,10,0.7) = 7 ?

sour fulcrum
#

Some code might involve using a Lerp with some kind of speed value, but that's not specific to lerping as its own concept

west sonnet
#

So if you wanted to move the lerp value from the first position to the second, you'd have to somehow increase the third value over time?

naive pawn
naive pawn
west sonnet
#

Right

naive pawn
#

(though not necessarily in seconds - think of it as a percentage)

#

t=0.5 means 50% complete

west sonnet
#

So then what I'm confused about, is how is this weaponPosition value changed, assuming "aimSpeed" doesn't change overtime weaponPosition = Vector3.Lerp(weaponPosition, adsPosition.localPosition, aimSpeed * Time.deltaTime);

sour fulcrum
#

lets say you have 10 apples in the fridge

#

I ask you to throw out the second half of the apples

west sonnet
#

oooohhh

sour fulcrum
#

then i ask you to throw out the second half of the apples again

west sonnet
#

Right, gotcha

sour fulcrum
#

weird example tbh im glad you understood it maybe 😭

#

it's modifying itself

west sonnet
#

Wouldn't that mean that you never reach the second value tho, you just keep getting closer and closer?

naive pawn
#

yeah lerp is deterministic. same inputs, same outputs. it's just math
so something in the input has to change for the output to change

naive pawn
west sonnet
wintry quarry
#

Lerp(a, b, 0.5) means the midpoint between a and b

keen dew
#

Lol literally half an hour banging about how it works had no effect at all

west sonnet
#

I figured it out! 😃

#

Ta Da

#

😎

#

Thanks for the help everyone

#

My first value was wrong. I was just finding the "t" value of the 2 points, so the object would stay stuck in place

wintry quarry
# west sonnet

Just FYI this is a sort of the classic "incorrect Lerp" and will work decently but it's not perfectly going to reach the destination nor will it be clearly configurable. Google "how to keep correctly in Unity" to read more

west sonnet
#

Yes, Chris sent a link about that earlier

#

Thank you!

grand snow
#

Only YOU can help stop lerp abuse

halcyon moon
#

what am i doing wrong here?

#

ah, solved it. just an upper case situation

#

i hate coding

timber tide
#

it's 2025, hook up your IDE and let it correct it for you

naive pawn
eternal falconBOT
cerulean sandal
#

hey i want to make a 2d game but i understood that i need to code alot and i dont know what to learn , isnt it c sharp

#

or is it c sharp for unity

slender nymph
#

c# is c# whether used in unity or not. there are beginner c# courses pinned in this channel and the pathways on the unity !learn site are a good next step to learn how to use the engine

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

cerulean sandal
gentle bone
#

you can try searching google for some C# Tutorials.. so you will learn the C# Basics... will still be very helpfull when using Unity .. then try the Unity Learn Website for deeper knowledge in Unity

tough shard
#

Hey can I ask Visual Scripting related questions here?

grand snow
#

oh look

#

a channel with the name

tough shard
#

Oh yeah I did do that, just had some basic questions

#

you didn't have to be that rude about it

#

but I understand

#

thank you

grand snow
#

people ask all kinds of non programming things here 😆

lethal owl
slender nymph
# tough shard thank you

please finish a thought before sending a message instead of spamming one thought across 4 messages

lofty canopy
#

Speech pattern police

slender nymph
strange jackal
#

so I am watching a video that shows creating a large collider around the objects to be picked up, like a stone. so that it triggers events when your in the collider, allowing you to interact and pick it up
however, since I am already using a Ray to look at objects and I added code to calc the distance before displaying the interact message
should I not just use my code based on my distance to objects then act on them? it seems like less code that the video's way

naive pawn
#

they're just different approaches that have their pros and cons

frosty hound
#

If your game is something like a third person perspective where you can pick up items "around you" , then a raycast won't suffice.

If your game is first person and you have to actually look at something, then it's fine.

If your game is first person, and you have to look at something but if you're near something there could also be a prompt, then you could/would use both.

timber tide
#

collider triggers are actually somewhat a pain to work with

#

if you can do it via physics queries I would

strange jackal
strange jackal
hexed terrace
rough granite
timber tide
#

You'd use shape overlaps here

strange jackal
strange jackal
strange jackal
hot wadi
#

What's the difference between getting tag property and using CompareTag()?

keen dew
#

CompareTag is marginally faster and it lets you know if you typo the tag name instead of failing silently

wintry quarry
hot wadi
#

Alright cheer mates. Thanks for info

umbral bough
#

Hey, I can't figure out how to access materials of a renderer:
var rend = GetComponents<Renderer>();
I am assuming it requires an assembly reference but I don't know which one.
These are the ones I currently have:

wintry quarry
#

var rend = GetComponents<Renderer>();
This code works fine but just note that GetComponents returns an array of Renderers. Using var here is probably confusing you.

umbral bough
#

oh 🤦‍♂️

#

I fully missed that, thanks

hazy dagger
#

how can i make it that the turtle actually touches the hitbox of the sneak before dying? currently it seems that it hits the empty pixels of the sprite, i have the same problem with another collission interaction

glad shore
glad shore
#

you should be able to change values in the component

hazy dagger
#

the box collider? it´s already small, the white outline

rich adder
glad shore
glad shore
#

ohhhhh

#

js make it thinner

rich adder
glad shore
#

what does IDE

#

what IS IDE vro

naive pawn
#

the thing you code in

rough granite
naive pawn
#

vscode, vs, rider, etc

rich adder
glad shore
#

I didnt know lol

rich adder
#

now you know 💫

glad shore
#

nav should i use a ai for my bosses or should i just write it myself

rich adder
#

its very Important to have a configured IDE if you plan on doing any work in unity, or anywhere else really

rich adder
glad shore
#

thx boss

hazy dagger
#

i still have the same problem with the portal, it teleports as soon as the sprites touch instead of when the portal collider gets touched

#

for now i´m using "yield return new WaitForSeconds((float)0.04);"

frail hawk
#

hehe

glad shore
#

there is no vc in this serv lol

rough granite
hazy dagger
#

i can make a vid

rich adder
#

is there a code question here , this is kind of a code channel

rich adder
primal trench
#

are abstract classes the best way to make a weapon sys?

rich adder
glad shore
primal trench
#

what are the pros and cons of abs classes then?

wintry quarry
primal trench
#

harcoding weapons

wintry quarry
#

your question is too vague

#

what does "hardcoding weapons" look like?

#

This is all way too vaguew

glad shore
# hazy dagger

are you sure its colliding with the correct collider, maybe the portal has a extra component which is making it detect early

wintry quarry
#

come back with some concrete ideas and code samples and then we can compare them

rich adder
#

look into Interfaces as well, they can also provide good modularity without the constraint of inheritance

wintry quarry
#

The phrase "weapon system" itself is extremely vague. That means something completely different depending on the game

glad shore
# hazy dagger

if ur adding by the int u can just detect whenever the turtle meets a certain pos instead of using collision detection

wintry quarry
#

The weapon system in Zelda Breath of the Wild is very different from the weapon system in Armored Core, for example

hazy dagger
#

when inactive the portal is disabled, the platforms is there so the player knows where the portals are

glad shore
#

what platforms?

hazy dagger
#

active and inactive

#

should i just make the platform a separate object?

glad shore
#

just add a portal png when its active

#

then disable the portal png when innactive

hazy dagger
#

the only thing the platform has is a sprite renderer

glad shore
#

give it a child object called "porta" then SetActive(bool)

hazy dagger
wintry quarry
# hazy dagger

why not just set those when it changes, instead of doing it each frame?>

rich adder
glad shore
#
if (active)
portal.SetActive(true);
if (!active)
portal.SetActive(false);
wintry quarry
#

portal.SetActive(active);

glad shore
#

that would be a more simople method

#

oop

#

LOL

rich adder
#

but yeah don't need to do it every frame

cosmic dagger
hazy dagger
rough granite
glad shore
#

put the code in the ontrigger

wintry quarry
#

you do it there

#

make a function instead of using a simple variable like that

#

or make a property

rough granite
wintry quarry
hazy dagger
rich adder
eternal falconBOT
hazy dagger
wintry quarry
#

llots of unecessary code duplication there

hazy dagger
wintry quarry
#
private void Awake()
{
    buttonRender = button.GetComponent<SpriteRenderer>();
    brightness = buttonRender.color;
    UpdateSwitchState(switchActive);
}

private void OnTriggerEnter2D(Collider2D collision)
{
    // Assign switchActive directly based on the collision tag
    switchActive = (collision.CompareTag("Player") || collision.CompareTag("Boulder"));
    UpdateSwitchState(switchActive);
}

private void UpdateSwitchState(bool isActive)
{
    float change = isActive ? 0.3f : -0.3f;

    brightness.r = Mathf.Min(1f, Mathf.Max(0f, brightness.r + change));
    brightness.g = Mathf.Min(1f, Mathf.Max(0f, brightness.g + change));
    brightness.b = Mathf.Min(1f, Mathf.Max(0f, brightness.b + change));

    buttonRender.color = brightness;
    portal1.active = isActive;
    portal2.active = isActive;
}```
nicely deduplicated^
hazy dagger
hazy dagger
umbral bough
#

Hey, how can I get the position of the object at the time of the collision?
I use Debug.Break() when the collision happens and can tell that objects are quite far apart at the time collision is registered, even with physics timestep being set to extremely low values like 0.001.
I tried subtracting collision point position from the current position in order to get the offset I would apply to that object, however, even tho it's calculated correctly, it gives me a position of the object where it would be if the position occured in the center of an object, not it's face/edge.
Is there a way to calculate this cheeply without complex code or do I just have to live with what I have?

// These are just relevant lines
                    var cPos = c.point;
                    var fragPosDelta = fragments[0].transform.position - cPos;
                        var fragPos = fragments[i].GetComponent<Renderer>()
                            .bounds.center - fragPosDelta;

In the pictures below, green sphere is where the collision occurred and third picture represents that the offset I get is correct by applying it to the object transform so its center ends up being at the collision pos.

Please @ me and thanks in advance!

glad shore
wintry quarry
glad shore
#

i forgot the on collision thing tho

umbral bough
hazy dagger
#

putting the teleportation code on the platform, with a smaller boxcollider still gave the same problem

umbral bough
#

I can send a link to these lines in the repo if that'd help for context

wintry quarry
umbral bough
wintry quarry
#

What are you trying to accomplish here?

umbral bough
#

since the collision

#

the screenshot I attached before has Debug.Break() right below the code I sent above and yet the objects are still quite far apart in the scene

umbral bough
# wintry quarry What are you trying to accomplish here?

I fracture an object when I collide with it and I want to apply the strongest force to fragments closest to where the collision occurred.
Issue is that the fragments move by the time collision is detected and the collision point stays where it actually occured.
Therefore, all the chunks are almost the same distance away from the collision point since they all moved equally from it and distance between them is tiny.
So therefore, I need to figure out where those chunks actually were when the collision occured.

strange jackal
#

so I googled how to stop Unity from recompiling every time I save code, but the instructions must be old, I don't see the ability to turn of Auto-Compile in the General Preferences?

umbral bough
#

As you can see in the picture, collision point is all the way to the left, quite far apart from the object at the time of detection.
Therefore, all the object chunks receive almost an equal force since they are equally far apart from the collision point.

umbral bough
wintry quarry
# umbral bough I fracture an object when I collide with it and I want to apply the strongest fo...

well the issue is that Unity's physics uses a discrete timestep. So the object is never actually in the position you are thinking of (exactly when the collision occurs). There is only basically a snapshot before and a snapshot after. I'm not sure the information you're looking for is really made available by the engine.

Maybe the closest you can get is to use:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.ContactEvent.html
And look at:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/ContactPair.GetContactPointFaceIndex.html

strange jackal
umbral bough
#

what I sent is a refresh in general, you'll have to press ctrl+r when you change the script if I am not mistaken if you enable what I sent

rich adder
#

thats pretty much the only thing you can disable for scripts

#

the playbutton domain reload but thats only for playmode

umbral bough
strange jackal
umbral bough
hazy dagger
umbral bough
hazy dagger
#

i tried to figure it out

umbral bough
#

oh

wintry quarry
hazy dagger
#

i made it a public float

umbral bough
#

yeah that's why

wintry quarry
#

why would it be a float?

hazy dagger
#

the code you showed had it as a float

umbral bough
#

do you understand how ternary works?

wintry quarry
rough granite
hazy dagger
#

making it a bool gives more errors

wintry quarry
#

WHy are you changing that code

hazy dagger
wintry quarry
#

that code is not relevant

#

you need to look at where you declare isActive

#

you did public float isActive;

#

why did you change that?
Nobody said to change that

rough granite
hazy dagger
rough granite
wintry quarry
#

but you are looking at the wrong code

#

you changed your other code for no reason

rough granite
hazy dagger
#

oh, ok, sorry

umbral bough
# hazy dagger no, sorry

ok, it's basically a shortcut for if/else.
so you would do:

// a float variable
float change =

// this is the same as saying if(isActive)
isActive ?

// if isActive is true return this
0.3f

// if isActive is false return this
: -0.3f

// if isActive assign 0.3f otherwise -0.3f
float change = isActive ? 0.3f : -0.3f
hazy dagger
#

ok, it should be good now

umbral bough
#

but isActive has to be a bool for that to work

hazy dagger
#

the portals don´t activate now, and the switch just gets darker and darker

rough granite
hazy dagger
#

onTriggerEnter2D

wintry quarry
#

there should probably be an if (isActive == switchActive) return; at the start of UpdateSwitchState tbh

wintry quarry
rough granite
wintry quarry
#

yeah this is wrong actually:

    // Assign switchActive directly based on the collision tag
    switchActive = (collision.CompareTag("Player") || collision.CompareTag("Boulder"));
    UpdateSwitchState(switchActive);```
hazy dagger
rough granite
wintry quarry
#

if should be like:

    // Assign switchActive directly based on the collision tag
    if (collision.CompareTag("Player") || collision.CompareTag("Boulder")) {
       switchActive = !isActive;
    }
    UpdateSwitchState(switchActive);```
rough granite
#

also no wonder

#

this


    private void UpdateSwitchState(bool switchActive)
    {
        float change = isActive ? 0.3f : -0.3f;

        brightness.r = Mathf.Min(1f, brightness.r + change);
        brightness.g = Mathf.Min(1f, brightness.g + change);
        brightness.b = Mathf.Min(1f, brightness.b + change);

        buttonRender.color = brightness;
        portal1.active = isActive;
        portal2.active = isActive;
    }

is wrong

#

the isActive for each bool here should be switchActive not the IsActive

wintry quarry
#

yeah the fact it's two different variables is basically wrong

#

it needs to be:

if (switchActive == isActive) return;
isActive = switchActive;
// the rest
hazy dagger
#

oh, i see what i did

#

😓

wintry quarry
#

switchActive would be better named newActiveState or something

hazy dagger
#

it works now

rough granite
hazy dagger
#

well, i learned some new things, thanks

#

after following tutorials for almost a year, of which they all ended up not working and the guys just changed code without saying anything, i just decided to make a game from scratch by myself, it´s been way more fun and i have actually been able to learn stuff

hazy dagger
compact sundial
#

im going a bit crazy with this, I did some stuff and somehow it keeps saying type mismatch when I try to get extended character controller in the inspector

#
using UnityEngine;

public class MagicBoltScript : MonoBehaviour
{
    [SerializeField] private float Speed = 1;
    [SerializeField] public GameObject ExplosionOnePrefabVariant;
    private ExtendedCharacterController extendedPlayerController;
    private float magicBoltDamageAmount = 1;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {

        extendedPlayerController.GetComponent<ExtendedCharacterController>();

    }

    // Update is called once per frame
    public void FixedUpdate()
    {
        transform.position -= transform.up * Speed * Time.deltaTime;
        //Debug.Log(transform.forward);
    }

    public void OnTriggerEnter(Collider other)
    {
        //Debug.Log(other + "Magic collides");
        if (other.TryGetComponent<Damageable>(out Damageable component))
        {

            magicBoltDamageAmount = extendedPlayerController.magicMissileDamageMultiplier + 1;
            Debug.Log("Dealing Magic Damage");
            component.Damage(magicBoltDamageAmount);
            Instantiate(ExplosionOnePrefabVariant, transform.position, transform.rotation);
            Destroy(this.gameObject);


        }
    }
}
#

extended character controller is a script that handles most of my character handling

wintry quarry
wintry quarry
#

another point - your extendedPlayerController.GetComponent<ExtendedCharacterController>(); line of code in Start() is completely pointless and does nothing

compact sundial
#

and the object that has the extended character controller is the player object

#

the player is in the scene and the prefab variant object is a projectile prefab

#

so that when the animation for the magic is used, the projectile prefab comes flying out of the player's hand

#

and the private field that I had was serialized but I unserialized it for the moment

#

it only shows the objects that have the extended character controller component

#

when I do the circle

wintry quarry
#

Prefabs cannot reference objects in a scene

#

The easiest approach here would be to pass the player reference to the magic bolt script (and any other spell script) after you instantiate the spell

compact sundial
#

oh lol I fixed it, I passed it the player prefab instead of the player in the scene

wintry quarry
compact sundial
#

it did tho

wintry quarry
#

it will "work" as in it will run without errors

#

it won't do the correct thing is what I mean

#

the position of the bolt will be incorrect, assuming the player can move.

compact sundial
#

no its working

#

I can record a little mp4 video rq

wintry quarry
#

Doesn't make sense unless your code is doing something else that you haven't explained

#
            magicBoltDamageAmount = extendedPlayerController.magicMissileDamageMultiplier + 1;
            Debug.Log("Dealing Magic Damage");
            component.Damage(magicBoltDamageAmount);
            Instantiate(ExplosionOnePrefabVariant, transform.position, transform.rotation);```
#

your code is not actually using extendedPlayerController's position at all
that's why

compact sundial
#
 public void FixedUpdate()
    {
        transform.position -= transform.up * Speed * Time.deltaTime;
        //Debug.Log(transform.forward);
    }
wintry quarry
#

Your original premise that you needed the reference to get the position was inaccurate

#

you're just using it to get the magicMissileDamageMultiplier

compact sundial
#

oh right, in another script I have it following the hand transform

wintry quarry
#

So in fact, if the magicMissileDamageMultiplier changes on the player at runtime

#

that part will not work here

#

you will only get the value from the prefab

compact sundial
#

its still working, its doing 7 damage like its supposed to

#
[SerializeField] public float magicMissileDamageMultiplier = 6f;
    private AttackType currentAttack = AttackType.Basic;
    public float DamageProperty
    {
        get
        {
            switch (currentAttack)
            {
                case AttackType.Basic:
                    return baseAttackDamageVar * (1 + basicAttackMultiplier);

                case AttackType.JumpSlash:
                    return baseAttackDamageVar * (1 + jumpSlashDamageMultiplier);

                case AttackType.ThrustSlash:
                    return baseAttackDamageVar * (1 + thrustSlashDamageMultiplier);
                case AttackType.MagicShot:
                    return baseAttackDamageVar * (1 + magicMissileDamageMultiplier);
wintry quarry
#

Again it will only not work if that value changes on the player during the game

compact sundial
#

oh

#

this code is in the extended character controller

wintry quarry
#

if magicMissileDamageMultiplier never changes, then it's fine, if a little weird

compact sundial
#

well it works for now so yay

bitter herald
#

Does anyone know how to get this to stop showing in my console? It keeps burying my actual errors and it's super annoying! -Shows after every compile, script change etc.

lofty canopy
rough granite
bitter herald
rough granite
bitter herald
#

Versions

slender nymph
bitter herald
rough granite
rough granite
humble ridge
compact sundial
#

just type 3 of these ` at the beginning and 3 at the end

pliant lion
#

how can i check if someone is from mobile phone or desktop in webgl game

primal trench
#

does anybody know how I'd do this in the new input system..?

humble ridge
#

Thanks! MI'm still a beginner but I'm trying to understand the physics system. I've been searching for alternatives for coding my characters 2d movement. I think that the best solution is using rigidbody addforce, so all the colliders works and so on (let me know if I'm wrong). So I applied the following code. But now it applies more force every time the key is pressed. It also slies when ending.

humble ridge
#
    {
        moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), 0).normalized; //Normalize to make diagonals same velocity as X or Y
    }
    void FixedUpdate()
    {
            rb.AddForce(moveSpeed * Time.fixedDeltaTime * moveInput); //Use deltaTime so move speed does not change if we change fixed update rate
    }```
#

I saw that changing linear clamping helps, but obviously it also changes the velocity when falling...

primal trench
#

a player input component

#

and a input manager script

rough granite
keen dew
rough granite
#

also you using ai for this?

rich ice
primal trench
prime shore
#

Anyone know the best way to add pixel art to Unity? I cant figure out how to match one sprite to another the pixels are always off

humble ridge
# rough granite also you using ai for this?

Well, I wrote this code based by a answer I got here saying that if fixed update values change, it will change my physics too I think, so that's why I applied this code, but I'm sure I didn't get it right, so that's probably why it's wrong

rich ice
humble ridge
prime shore
#

oh my bad i thought this was unity beginner

humble ridge
rough granite
keen dew
#

I'm not sure what kind of example you're looking for. Change the values and see what happens

humble ridge
#

I feel that I'm not understanding well the physics and I don't know where to look

primal trench
humble ridge
humble ridge
rough granite
#

which isn't even half the function call yet it's only random if statements

rich adder
humble ridge
primal trench
humble ridge
#

Now I've been programming for over 8 years, but when I started I remeber programming even worst things (but I'm new to Unity :p)

rich adder
short hazel
primal trench
#

like how do i transfer

primal trench
#

the getkey and getkeydown stuff to this way of input

rich adder
primal trench
rich adder
#

if you want held you would use started and canceled / performed depending on mode

#

polling is an option too but Idk how to do that besides Keyboard.current.

primal trench
rich adder
primal trench
rich adder
primal trench
rich adder
#

Just call whatever method you need for the R key OnReload and OnShoot

#

eg

OnFire(InputValue value) {
weaponScript.Shoot(); }
...
void Shoot(){
if(ammo == 0) return;
//Shoot stuff```
primal trench
rich adder
#

as I said before you can also use a bool field to store the state of the action

primal trench
#

thanks

rich adder
#

as you might tell lol

primal trench
#

ik i usually work in godot so this seems so much more complicated 😭

rich adder
#

it seems so because this is a swiss army knife, the old input system was more like a butter knife

primal trench
#

in godot you just do this and call if input.isactionjustpressed("input")

rich adder
#

you can do the same exact thing 🤷‍♂️

#

you're just not used the interface / workflow ig

#

It also offers the options to use hardcoded strings but thats ugly

primal trench
#

yeah i've played with unity for awhile i always just hated the input system and never learned it properly out of pure spite

rich adder
#

well you're doing yourself a disservice, especially when dealing with how easy it is to do rebinds and auto device detections so you can switch menu UIs on the fly.. cool stuff

acoustic belfry
#

Hi, i need help

for a weird reason the debug log for i guess is not zero and the should work is not called, why that happens

    {
        Debug.Log("meele's call'd");
        Vector3 meleeRange = new Vector3(attackRangeX, attackRangeY, attackRangeZ);
        int hitsCount = Physics.OverlapBoxNonAlloc(meleePos.position, meleeRange, hitDemons, Quaternion.identity, demons);

        for (int i = 0; i < hitsCount; i++)
        {
            Debug.Log("int is not zero, i guess");
            if (hitDemons [i].TryGetComponent<EnemyBase>(out var enemy))
            {
                Debug.Log("THIS SHOULD WORK");
                enemy.TakeDamage(meleeDamage,0,2,2,transform);
                // Don't set HasHitValeria = true here if you want to hit all targets
            }
        }
    }```
#

just melee call'd

#

im trying to check what went wrong, but i dont find it

#

constant melee checking and 3D ends up to be very complex i supose

rich adder
rich adder
#

nothing to do with that

acoustic belfry
#

i resize it and ends up for the int is not zero now works

rich adder
#

if it was a problem a lot of games wouldn't exist lol we'd be playing pong

acoustic belfry
#

but the last one doesnt

primal trench
rich adder
# acoustic belfry but the last one doesnt

so its not finding the component you mean from tryget ?
instead of logging stuff like "work" and "not work" debug the values, like debug what you hit in that loop and see if its what you expect to be

acoustic belfry
#

ok

rich adder
acoustic belfry
#

all of em inherit from it

rich adder
acoustic belfry
#

ok

#

all of the scripts are inherited from EnemyBase

rich adder
#

see which colliders are catching and what components those have

acoustic belfry
#

in the 2D old project this worked

#

and the script was similar

#

atleast that part was the same

#

check if it has the component enemyBase

#

and it had it

primal trench
rich adder
acoustic belfry
#

yes i suposse

#

is the script

rich adder
#

Debug.Log hitDemons [i].name

acoustic belfry
#

holup

rich adder
#

make sure ig

acoustic belfry
#

i hate 3d, now im starting to think

#

it may be not

rich adder
#

whats 3D got to do with it lol the code is exactly the same

acoustic belfry
#

i mean, its an empty body, inside of it is a capsule

#

the object has a rigidbody

#

but the capsule has a collider

#

no, cuz on 2D the colliders are in the same object as the parent

#

but in here is the OBJ

rich adder
#

TryGetComponent only looks for the components on the collider object not Parents

#

rigidbody shouldn't affect that

acoustic belfry
#

i changed opinion

#

the spherecast works

#

so it should work

#

my internet is trash

#

Y E A H

acoustic belfry
#

it was freaking that

#

the parenting

#

well, thanks a lot

#

this helped a lot

rich adder
primal trench
#

mhm

rich adder
#

You can use the isPressed from InputValue then

#

just set button to detect both Started and Released Set action type to Value

#

should automatically set the bool to false when let go cause OnFire

primal trench
rich adder
primal trench
# rich adder the what now ?

the variable that decides if like, if you can hold and continuously shoot or you have to press the shoot button over and over for each shot

earnest wagon
#

so. oddly specific question. Suppose I want to make an editor only component, which has different behavior if one of two packages is present in the project, and a third behavior if both are present, and another if neither is present. I know there is, in some languages, the concept of lazy loading, but I'm not really savvy with c# aside from general familiarity with it via c/c++ relation and java similarity. is this possible without going kersplode?

The two packages are Magica Cloth 2 and Dynamic Bones.

lofty canopy
#

I don't mean 8 lines in a row but 2-3 is acceptable, yeah?

#

I'm just saying I might get excited about a topic and I'll forget the etiquette in the moment cause I'm a ADHD space cadet sometimes. lol

eternal needle
rich adder
primal trench
rough granite
lofty canopy
#

Let's not make it sound like a special enum then.

rough granite
lofty canopy
#
public enum InteractionType
    {
        None,
        SingleShot,
        BurstFire,
        SemiAutomatic,
        Automatic
    }

//You can also bitshift the numbers so you can do binary comparisons.
public enum InteractionType
    {
        None = 1,
        SingleShot = 1 << 1,
        BurstFire = 1 << 2,
        SemiAutomatic = 1 << 3,
        Automatic = 1 << 4
    }
#

There's an example for you.

earnest wagon
neon forum
#

can I not add gameObjs in the scene to prefabs?

wintry quarry
neon forum
#

that is, and darn

#

I'll figure something else out then

#

Is there a way for a function in a script in a prefab to "talk" to a gameobj in a scene?

lofty canopy
#

For the most part a prefab is a predefined collection of gameObjects and components. anything from the parent of the prefab to the children can reference each other but anything outside of the prefab can't be saved indefintely.

wintry quarry
neon forum
#

I'm trying to have an onclickevent to basically tell the deck editor to add 1 copy of a card to the decklist

rich adder
lofty canopy
#

You'd have to have the prefab in the hierarchy and you can temporarily set a reference with a SerializeField.

wintry quarry
lofty canopy
#

Would using an Event and subscribing work here?

neon forum
#

like creating an instance of the script to be globally referenced?

wintry quarry
#

then you have a static accessor property to get the reference

neon forum
#

ahhh that could work, but I won't need it except for the deckeditor scene, so it'll still be destroyed when I leave the scene, will that be okay?

wintry quarry
#

As long as you only try to access it when it exists

neon forum
#

ah, then good

wintry quarry
#

you could also have the card fire an event and have something in the scene subscribe to it when you spawn the card

neon forum
#

I mean I'm going to have a lot of cards in the 'selectable card section', would events allow me to fire them off with their name/instance?

lofty canopy
#
using System.Collections.Generic;
using UnityEngine;

public class SingletonExample : MonoBehaviour
{
    public static LevelGrid Instance { get; private set; }

    private GridSystem gridSystem;

    private void Awake()
    {
        if (Instance != null)
        {
            Debug.LogError("There's more than one SingletonExample! " + transform + " - " + Instance);
            Destroy(gameObject);
            return;
        }

        Instance = this;
    }
}
#

There's an example of a singleton for you. There's various ways of doing it though.

earnest wagon
#

like its honestly very easy to detect MC2; it defines a symbol in the project, MAGICACLOTH2

eternal needle
wintry quarry
neon forum
#

I can't do whatever I want because c# will tell me "no you can't do that"

#

I can try for sure

wintry quarry
lofty canopy
#

Oh, btw with that singleton example you can type SingletonExample.Instance.MethodExample() or SingletonExample.Instance.variable if you make them public.

eternal needle
earnest wagon
#

sure NEED is one thing but it does make it easy

#

ah, and tbh, misspoke. while they're available on the unity asset store and can be installed via the package manager they're not 'packages' so to speak

eternal needle
#

oh I guess it does change if you're trying to reference the specific components

lofty canopy
#

But, generally the singleton pattern tends to be avoided except in certain situations. creating an Event and subscribing to it is the cleaner method.

neon forum
#

I'll try to learn events then

#

so doing a += and a function is like assigning an event to when something happens in the game?

eternal needle
#

🤔 singleton and events solve entirely different problems. An event would live on an instance (unless for some reason you make it static)

wintry quarry
#

Singletons are very common

neon forum
#

events would be better then since these will be instances made from prefabs

lofty canopy
#

You're adding that method to the event to be called when the event is fired off.

eternal needle
#

what instance of the event would you be subscribing to -> now you're back to the real problem here that you need to reference an instance

neon forum
#

so the event would be OnClick() for this button

#

I just need the instance's name

wintry quarry
#

You can solve it in either way. Singleton will be less code and simpler. Managing events will involve managing instances and subscriptions for all the objects you instantiate

#

Take your pick

#

You could use a static event as well

#

that would be an in-between solution

neon forum
#

event seems like the optimal solution

eternal needle
#

Unless im missing some context, I didn't see you describe much about what the setup or problem is. Are cards just supposed to call a function on the DeckEditor while in the DeckEditor scene? Are you re-using the same cards in other scenes where you might not have a DeckEdtior?

lofty canopy
#

Oh, and usually it's a good idea to subscribe OnEnable and unsubscribe (-=) OnDisable.

neon forum
#

I have a prefab that basically is told by the deckEditor to copy itself into every instance of Card(Scriptable Object) in Resources/Cards

#

I was able to do that successfully

grand snow
#

un sub in OnDestroy() if done in a monobehaviour

#

because it wont magically un sub itself!

neon forum
#

now I need to tell each card to "tell deckeditor to add a copy of yourself to the currect deck"

wintry quarry
#

to be clear to use events you will need to do this:

  • When you instantiate the prefab, you will need to subscribe to the event on it, which will need to pass itself as an argument.
  • When you press the button, the card needs to fire that event, which will fire the subscriber
  • When the card is destroyed you will need to unsubscribe from its event

To use singleton it will go this way:

  • When the button is pressed, it gets the singleton reference and calls a function directly
neon forum
#

Where would I create this new event? In deckeditor?

wintry quarry
#

no... on the card UI prefab

#

In either case the thing you set in the inspector (button listener) will need to be a function on a script on the card ui itself

neon forum
#

So a new event e(this) and then CardUI.button += event e?

wintry quarry
neon forum
#

so OnDestroy I need to unsub

grand snow
#

This way round its not essential to unsub as we can presume CardUI wont invoke its event any more after being destroyed...

lofty canopy
#

You should make the cards scriptableobjects if you haven’t.

neon forum
#

do not worry I have

wintry quarry
#

true actually, if the button's lifecycle is less than the deck manager, you don't need to unsub

eternal needle
lofty canopy
#

Is there a way you can share the project so we can look at it? Edit: Don’t do this.

neon forum
#

the whole project?

#

I mean I need to boot up my gitbash but give me a bit

eternal needle
#

you do not need to share the project, and shouldnt either. I am asking specific questions about the design

neon forum
#

ah

lofty canopy
#

Fair enough. Noted for next time.

eternal needle
#

i ask because it seems like this is your real problem at the end: You have cards that should do logic only if its in the DeckEditor scene.
The question is what this logic is. Should it just call a function on DeckEditor? Is DeckEditor calling a function on the cards? What does it actually mean for "deckeditor to add a copy of yourself to the currect deck"

neon forum
#

Essentially, in the DeckEditor scene, the player should be able to:

  1. view a list of "available cards", which is created from the DeckEditor creating a card(from the card/button prefab) for each instance of card in resources/cards
  2. Upon clicking, the card should tell the deck editor to add a "copy" of that card to the decklist(in code it just tells the deckeditor to add the card, not the prefab, to the list of cards). The "Current deck" should then display the same prefab, with the option for the player to click on it to remove it from the current decklist.
  3. upon finishing, it should have a decklist that the GameManager can read and create a deck from
#

the card prefabs and deckEditor script are done and are deleted upon leaving the scene

#

Maybe I should do something with pictures because I'm terrible at explaining with words...

#

would you rather have me draw it?

grand snow
#

A single card instance having an event to report when it was clicked makes sense to me

#

makes sense also that deck editor creates the instances and also handles responding to said events

spring otter
#

Say I have a directional Vector(0, -1)
Is there an operation I can make to rotate it by angles or something like that? So that I can, for example, rotate it by 45, 30 degrees and odd amounts?

grand snow
spring otter
#

Quaternion.AngleAxis

lofty canopy
#

Quaternion.eulerAngles is easiest to work with.

grand snow
eternal needle
# neon forum Essentially, in the DeckEditor scene, the player should be able to: 1. view a li...

what you described makes sense assuming you have this decklist already defined and accessible somewhere.
Events could make sense here and it'd be easy enough. I'd consider using an ID instead of name incase you ever consider changing card names in the future.
My only concern here is if you're re-using these cards UI's for other scenes that need to handle the OnClick logic differently. It might get pretty messy

grand snow
#

Their description of the current deck editor design is fine

#

using singletons here would be dumb and im glad they arent

neon forum
#

and thus give it different logic based on the scene

grand snow
#

If this was me, a "Card" would just do one job: show the sprite for a card and store what card it is and have an event for being clicked

neon forum
#

Well that's the scriptableasset

#

that's its only job

grand snow
#

Then you can re use this anywhere you want and not worry soo much

#

Well yea we can have the "card data" and "card view" if you prefer

grand snow
#

Then its all good 👍

neon forum
#

It basically says "i've been clicked" and the deckeditor/gamemanager handles the rest

grand snow
#

public event Action<Card> OnClick; 🙂

neon forum
#

I just need to figure out the event system so I don't screw everything up

eternal needle
#

from the current idea it sounds like a card would be invoking an event specifically passing it's name, but yea if it passes just the card instance then it is fine

grand snow
#

some unique id or the data object works, programmers choice

neon forum
grand snow
#

Yea, as it creates instances it can subscribe so it can respond to a card view being clicked

#

spawn card view, init card view with card data, sub to event

#

or however these prefabs work

neon forum
#

so I tell the DeckEditor to subscribe to the event of the instance

grand snow
#

yea

#
CardView card = Instantiate(cardViewPrefab);
card.Init(cardData);
card.OnClick += OnCardClicked;
spring otter
neon forum
grand snow
spring otter
#

I don't understand

eternal needle
spring otter
#

I never worked with Quaternions before

grand snow
spring otter
#

Ah, I was using the *= operator and Unity was complaining

#

Thats why I was reading the components

eternal needle
# neon forum

you should google how to use events in c#, like how to subscribe and unsubscribe
you dont invoke the method when adding it. dosomething also need to be a method

spring otter
#

It worked guys, thanks for the help

grand snow
neon forum
#

I figured it out

#

I didn't need to add the parenthesis because that caused problems

grand snow
#

yea you arent calling the function, just using it in the event sub

#

its like when we do nameof(MyCoolFunction)

neon forum
#

ahh

rough granite
neon forum
#

how do I mass unsubscribe from the instances? Do I do a foreach or is there a quicker option?

grand snow
#

string name = nameof(MonoBehaviour);
produces a string of the symbols name

polar acorn
# rough granite what is this used for?

Used for things like Invoke or StartCoroutine that take a string name of a function as a parameter, but it gives you compile-time checking and makes it so if you rename the function you don't need to remember to go back and change this as well

rough granite
polar acorn
#

Things that show up in blue in VS

rough granite
eternal needle
neon forum
#

ah, then good, because yeah it is destroyed on scene change

polar acorn
rough granite
grand snow
neon forum
#

yeah I was thinking that I'd have to have a list or something that would point to all the instances

#

but that sounds like an even bigger mess

bitter herald
grand snow
#

Its more of an issue if you did:
card.OnClicked += (card) => {//stuff}

#

(using a lambda expression)

#

You are currently fine as you can use the same function to unsub inside of card editor.

neon forum
#

do I need to assign the OnClick event to the button component?

#

I don't think the OnClick is firing

grand snow
#

if you have a button then you need to invoke your event somehow

#

button.onClick.AddListener(() => OnClick?.Invoke(cardData));

#

presuming button is a UGUI button

neon forum
#

it is, thanks

grand snow
#

event?.Invoke() this lets us invoke the event and avoid a null ref exception if it has 0 subscribers
otherwise you can do event()

neon forum
#

Alright, so I added that as well. My button isn't working though, so I gotta see if something's blocking its on click

#

yeah it has the button component but it's not firing onclick? How do I see if there's something blocking it?

lofty canopy
#

What’s the difference between Euler and eulerAngle?

slender nymph
neon forum
#

how do I select the eventsystem?

wintry quarry
slender nymph
lofty canopy
#

I always found eulerAngles worked for me. Quaternion is difficult for me to understand.

slender nymph
neon forum
#

yeah but like where? It's not in the heirarchy

wintry quarry
#

then you don't have one

slender nymph
#

well then that is precisely why your button isn't working

lofty canopy
#

EventSystem is created when you create a canvas, yeah?

neon forum
#

yup it work snow

#

it didn't

#

had to manually add one

slender nymph
#

you probably deleted it by accident. or you created the canvas manually rather than through the Create menu

wintry quarry
#

Or copied your UI elements from another scene

slender nymph
#

or that, yeah

lofty canopy
#

Can you safely child the EventSystem to the canvas game object for the purpose of prefabbing?

wintry quarry
#

Depends

#

I wouldn't recommend it generally

#

It's very common to have more than one canvas in a scene

lofty canopy
#

And you only need one EventSystem?

wintry quarry
#

yes

#

you should only have one

primal trench
#

i know you can check if a collider enters a trigger area on a collider with entertrigger(), but ;lets say i want the trigger to check it instead, how would i do thay

wintry quarry
lofty canopy
#

Do you have a nifty link that explain how the EventSystem can be modified or is that not necessary?

wintry quarry
#

You can use OnTriggerENter on either object involved

primal trench
#

thanks

lofty canopy
#

I could probably google it but if you know something that’s very concise that would be very much appreciated. 🙂

wintry quarry
neon forum
#

Eyy I did it and it added to the decklist

lofty canopy
#

Just understanding what you can do with EventSystem.

wintry quarry
#

You can write custom input modules and custom raycasters

#

there's not much you can do with the EventSystem directly

lofty canopy
#

Ah ok, fair enough. Thank you.

#

What would be the purpose of custom scripts? What would that achieve?

wintry quarry
#

scripts?

#

what kind of scripts?

lofty canopy
#

Modules and raycasters sorry.

lofty canopy
#

Awesome, thank you. 🙏

rough granite
#

wanna explain what this means for the uninformed :?

slender nymph
#

that's just the version number for the UI package

wintry quarry
rough granite
slender nymph
#

yes, it has been for a couple of years now (assuming you mean the UI package being separate from the engine core)

wintry quarry
#

All packages have their own independent versions from the Unity version, yes.

rough granite
#

yeah sorry i was just curious cause i'd never heard of it and thought it was a seperate app to develop UI's

lofty canopy
#

What’s the new UI system called? Looks really customisable?

slender nymph
#

note that what praetor linked is just the regular Unity UI package, not UITK and is not new.

rough granite
lofty canopy
#

It’s amazingly customisable but you need to know css and stuff.

rich adder
#

its very xml / css-ish friendly

#

but you can also just use c#

slender nymph
#

unfortunately still missing a few features that ugui supports though, like shader support

rich adder
#

yeah still doesn't feel 100 there yet..didnt they only recently put world canvas or somethin

north kiln
#

6.3 has shader support in the form of custom USS filters (which apply to stacks of UI using render textures), and afaik later in 6.3 they'll be releasing shader support generally

halcyon moon
#

guys why when i create a script called "GameManager" the script is in a setting logo theme and called a mono script?

#

unlike other scripts

bright zodiac
north kiln
#

There's nothing to fix, if you are asking if custom z-index is a thing, then no

bright zodiac
#

ah so no z-order still.. sad face

slender nymph
# halcyon moon

the gear icon is just a quirk of older unity versions for scripts called GameManager. it was patched out in like 2022 or something like that. as for why it shows it is called a mono script when you select it, that's the asset type for all of your script files

halcyon moon
#

then no problems? just a visual bug?

ocean matrix
#

is there anything wrong?

rich ice
#

not a code question. although other than it being disabled, no

teal viper
#

Could you even disable transform..?

ocean matrix
#

wait your not allowed too?

rough granite
ocean matrix
#

am i gonna get banned

teal viper
#

I thought it was physically not possible.

ocean matrix
#

my friends keep saying its wrong?

teal viper
wintry quarry
#

photoshop is my guess

halcyon moon
frosty hound
#

Show what value you've set for the delay in the inspector

#

But also, you call Restart() before you invoke it, which is of course, instant.

halcyon moon
#

how so?

#

i set a value of 1 sec for the invoke

#

but also how did i call it early in the code?

rough granite
frosty hound
#

Read the few lines you have?

#

You call Restart() and then call Invoke.

#

Also, setting a public to a default value in code isn't guarunteed, as the inspector value will override it. Regardless, that isn't the issue here (but a potential future one).

halcyon moon
#

well i just flipped them but nothing got fixed

frosty hound
#

Of course, because you're calling Restart()

#

Just think for a moment instead of flailing around. Why are you even calling Restart() in addition to your Invoke?

halcyon moon
#

well then how do like make them seperatly?

#

i still can't like form a proper code by myself yk

#

i just started learning

rough granite
halcyon moon
#

and it well just work?

#

but how will the line get called?

rough granite
frosty hound
#

When you use Invoke it calls the function you typed in there, after the amouint of time you specified. That's its purpose.

halcyon moon
#

ahhhh

#

now i understand

rough granite
#

thats what it's there for cause unlike coroutine or async / await it doesn't pause that function from continuing

halcyon moon
#

yep it worked

sour fulcrum
#

Imagine telling your friend to come help with something then immediately telling him to come help in 5 minutes

halcyon moon
#

sorry for my lack of braincells

#

but yk smth new everyday

sour fulcrum
#

If your trying to learn there’s never a need to apologise 😄

halcyon moon
#

ur right

#

thanks also to you guys

rough granite
sour fulcrum
#

imo its pretty easy to tell if someone is trying to understand what their being told

halcyon moon
#

i will try from now on to like read the code and understand it

tawny mortar
#

I been blessed by the coding gods because unity decided to not give me a error in the last 10 minutes

balmy vortex
#

Hey so like I need to make the fireball prefabs I spawn come out slightly infront of the player so it doesn't push them (like in the video vvvv) but I'm not sure how to actually get the direction of the camera to know where "infront of the player" is

#

tldr; the bullet pushes the player when shot in certain directions. bad.

lofty canopy
#

position of the fireball should spawn from the player. You can add a empty gameObject child to the player and put it offset infront of the player and use that as the position to Instantiate.

#

@balmy vortex

#

That way when the player rotates the empty gameObject (call it weaponSpawn?) will rotate and remain in front of the player.

balmy vortex
#

cuz like rn I'm just using the players position since the script is technically a child of it

lofty canopy
#

What is PlayerSpells attached to?

naive pawn
lofty canopy
#
[SerializeField] private Transform weaponSpawn;

Then go back to unity and drag and drop the weaponSpawn gameobject in the new field for PlayerSpells.cs.