#💻┃code-beginner
1 messages · Page 713 of 1
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
that sounds better than what you said before
but nothing wrong with what i said too, so the whole conversation is actually redundant
I mean, that is what I said before. I basically led with that.
The problem with what you said is that it implies FixedUpdate makes things more performant
if you have a higher physics tick rate than framerate, then fixedupdate would make it perform worse, technically
not sure what you're trying to argue here - the "if you use FixedUpdate" part makes it wrong
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);
}
}
}
if the particles are a child then do SetActive() on the light gameobject instead
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
Yeah...thats what I was typing
so the solution is to SetActive() the main parent
FireParticleSystem?
I would prefer to keep the torch + torchholder in the game.
Does setActive remove them?
yea, SetActive() will deactivate and activate the gameobject
.enabled = true/false will deactivate and activate the component
it changes the active state of the gameobject which then affects its components and child objects
This is day 1 stuff
may could build the particle system over the torch and then when u disable it u have the placeholder there in place behind it
I knew what setactive did prior
Thank you for your help. I will try different approaches
hello I need help how could i fix it. It doesnt show the code and I couldnt edit it
drag the script from the unity editor to visual studio
make sure you correctly set up your !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
you can double click a script in the unity editor and it will open in the configured IDE 💡
sometimes it doesnt work or will open a blank visual studio on slower devices, the drag tends to always work
miss configuration is the cause, a drag + drop may just open the file as a "miscellaneous file"
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
is selectionTransform null? no? then is there an InteractableObject script in it? yes? then what is GetItemName() doing?
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>();
}
how is this any relevant to the last code? also does IteractionText (spelled incorrectly btw) have a Text script?
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
shouldn't use lerp for movement
its where I declare the interation_text
but the key problem is when I add the .text
I am trying to update the text in in a text box on a canvas
yeah but what is the class type i guess sorry bad with words but send the declaration of it
the InteractionText game object is a Text box
it should be "TextMeshProUGUI" as far as i know
wdym?
dont use lerp for movement simple as that
i mean i guess you can but far too many people use it wrong
You don't get the mouse screen position from the mouse anywhere?
now the following code
interaction_text = InteractionText.GetComponent<TextMeshProUGUI>();
has error message
can't convert type
maybe give the whole !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Heres what i did
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.
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
Pointer as in mouse?
if so just this will work
private void OnMouseOver()
{
}
Thank you
That function still works.
The documentation was simply moved to the UI package documentation site.
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.
(We don't know what MoveToPoint does)
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;
}
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)
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.
How do I make something move randomly?
It just removes the need for private bool isDragging etc.
go check !learn first.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
if you've already done that then it should be simple enough using a navmesh and a few pre-defined nodes
What unity version should I download?
usually you'd want to pick the latest LTS version
You have two methods of Randomization, both are pseudo-random generation.
There's Unity's Random function or C# System.Random.
✅ 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...
So the latest LTS is 6.0, time to get that I guess???
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.
when will it end support?
I just haven't got there in the code so when I click again, depending on the context of the location, it will either return the card where I picked it up from or place it in the placement zone. I then plan to set selectedCard back to null so I can grab another card, etc.
Yeah no stress, Just pointed it out in case that was a new insight to you, keep cooking 😄
hit.collider will never be null?
Ah, you are correct! I guess some people can be wrong on the Internet.
.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
That's the only bit of code I was like "Eh, whatever" and chucked it in, not really thinking about it.
ye its a hyper-nitpick dw
but yeah, how would I go about changing the x and y position ratios the further I move to the edge of the screen?
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
@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.
how would I go about accessing a bool from another script without having to add a reference every instance?
It already is
you need to reference every instance, why does that trouble you?
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
Referencing the specific instance is the preferred approach but if there's a lot and you're wanting to decrease repetition, you could probably have some sort of Singleton manager reference all instances and everyone else simply access those instances from the Singleton manager.
You can probably just use https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html directly rather than raycasting which might provide a more consistent/accurate point?
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
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.
what do you mean directly instead of raycasting?
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
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
You could probably set the field when the player picks it up
I saw something about that but didn't try it yet. I'll give it a whirl.
would something like this work?
You can find the player with the Player tag
player = GameObject.FindGameObjectWithTag(PLAYER_TAG);
and just set a private static String PLAYER_TAG = "Player"
in this case the "player" is just the controller script
does the gameobject have the Player tag set on it?
That would work too, and search for PlayerController.
yes, or else the cube will teleport to the player anytime it touches anything
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.
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.
you could also do something like this
isInTrigger = other.TryGetComponent(out player);
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
What's the best way to move the players weapon into an ADS position from hip firing? Would Lerp be good for that?
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
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?
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
·············································································...
Looks like you've offset it during runtime. Maybe show any code that has changed it's position.
The only code I have right now that affects the weapon position is in Start(), and that's just to set the position to HipFire
If you comment out line 56 does the unwanted behavior persist?
So it's whatever value that's being set there that's moving your gun to the unwanted position.
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
Depends if you're using localposition values or whatever..
yeah it should be transform.localPosition = ...
a little bit outdated but also has some helpful content
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
With LocalPosition, the gun still doesn't go to the exact position
That's what I'm doing. I've got empty gameobjects and using the their positions
But in the code you have Vector3 variables
This is with transform.localposition
Yeah, is that okay?
It's because I wanted to use Lerp to move inbetween hip fire and ADS
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
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
That's a different problem
The gun was placed where you asked it to be placed (dead center relative to it's parent)
I thought I asked it to be placed at the hipfire gameobject position 😭
Just naming the variable "HipFirePosition" doesn't mean it has anything to do with the object called "HipFirePosition"
Omg I've just realized, when I changed the variable from Transform to Vector3, it unassigned the gameobject
that would make sense, gameobjects are not vector3's
Is there any way for me to assign the gameobject to the vector3? In the inspector, the vector3 are now X,Y,Z values
Is it possible to use the transforms of the objects in Lerp?
To Lerp the gun from one position to another
Yes, just the same as with any vector3. They aren't anything special
so where else can i learn from?
research. there are many tutorials and documents, create small games like flappy bird , temple run etc
!learn and there are more links in the pinned messages
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks guys, so it comes naturally while learning other things?
What is "it"?
the skill and key to the language
but yeah the pinned masseges have good guides in them
So why do I get this error?
Vector3.Lerp takes in vector3's
Because those are the object transforms, not their positions
if i asked you to stick your toe in the pool and you jumped in the pool
Also that lerp is way wrong even if you fix the parameters
How so?
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
eg.
Lerp(0, 10, 0.25f) = 2.5f
Lerp(0, 10, 0.5f) = 5
Lerp(0, 10, 10) = 10
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);
}
Okay, this is a little confusing to follow. How can Lerp be used to move an object then?
and on mouse click swap isHipFiring between true and false
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
Typically you make a timer from 0 to 1 and use the timer value when lerping
So with the lerp value at 1, the object with immediately jump from the first position to the second. Is that right?
(if thats what your using the lerp for)
but in this case MoveTowards is easier and you don't need to worry about the intricacies
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"
How can that be used for movement tho?
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
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);
So does "t" act like a slider in between the 2 points?
As in "t" represents where the variable should be between the 2 points
Yup!
A lerp is commonly used when actually implementing sliders too 😛
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);
what do you mean by "fixed value"
In the line above, "aimSpeed" will be a fixed value, right? Let's say it's 5. Which means weaponPosition will always be the same value between the 2 positions because aimSpeed never changes
aimSpeed is a variable. we have no idea if it changes or not
but regardless it being fixed or not doesnt really matter
that's wronglerp
the third value is just the slider between the first two values
Applying lerp so that it produces smooth, imperfect movement towards a target value.
it's basically using the math of lerp to do something that isn't actually lerp
But doesn't that mean weaponPosition never moves from one position to the other?
Because aimSpeed doesn't change
so you can't really read the third parameter as t here, because it's just not following what lerp is intended for
Assuming it doesn't
but weaponPosition does
It changes by the value of aimSpeed?
no, weaponPosition itself changes
@west sonnet go give this a read
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
Okay, I kinda get it
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?
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)
Ooooohhh
lerp doesn't have a speed
lerp just gets a value in-between 2 other values
Lerp(0,10,0.7) = 7 ?
Some code might involve using a Lerp with some kind of speed value, but that's not specific to lerping as its own concept
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?
the speed comes from how quickly you vary the value of t, at least with the "correct" usage of lerp where a and b don't change
yep, that's what t stands for, time
Right
(though not necessarily in seconds - think of it as a percentage)
t=0.5 means 50% complete
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);
lets say you have 10 apples in the fridge
I ask you to throw out the second half of the apples
oooohhh
then i ask you to throw out the second half of the apples again
Right, gotcha
Wouldn't that mean that you never reach the second value tho, you just keep getting closer and closer?
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
yes, that's mentioned in the article i linked you..
Why does the weapon move about halfway then doesn't move anymore even with the mousebutton held down?
Because that's literally what your code is telling it to do
Lerp(a, b, 0.5) means the midpoint between a and b
Lol literally half an hour banging about how it works had no effect at all
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
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
Only YOU can help stop lerp abuse
what am i doing wrong here?
ah, solved it. just an upper case situation
i hate coding
it's 2025, hook up your IDE and let it correct it for you
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
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
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
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
so on these channels i can learn c sharp and c sharp for unity
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
Hey can I ask Visual Scripting related questions here?
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
people ask all kinds of non programming things here 😆
was about to say the same
please finish a thought before sending a message instead of spamming one thought across 4 messages
Speech pattern police
actually it's a server rule. #📖┃code-of-conduct
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
they're just different approaches that have their pros and cons
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.
collider triggers are actually somewhat a pain to work with
if you can do it via physics queries I would
ya, it's third person, and I wasted a couple of hours until I realized my ray was hitting the back of my head... so I offset the camera so it sees past
that's what I was thinking
use layermasks, so rays only hit what you want them to
for the first instance you could make a raycast off the player and not camera, though picking "around you" wouldn't work
You'd use shape overlaps here
I had that at first, but it wasn't always the center of my screen the character moves around
layermasks? I'll look into that
although I have changed it, my character was able to face different directions than my camera view. so the direction my character was facing was not the same as the camera view.
What's the difference between getting tag property and using CompareTag()?
CompareTag is marginally faster and it lets you know if you typo the tag name instead of failing silently
when you call tag it has to allocate a new string which will need to be garbage collected later.
Alright cheer mates. Thanks for info
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:
WHy are you assuming an assembly definition is required?
var rend = GetComponents<Renderer>();
This code works fine but just note thatGetComponentsreturns an array of Renderers. Usingvarhere is probably confusing you.
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
you should download CSharpier or Prettier extenstion on vscode is puts less of a hassle and makes code easier to understand
change the hitbox
you should be able to change values in the component
no what they need is to configure their IDE..
you said a big word that i dont understand 🙏
wdym a big word?
the thing you code in
IDE is the code editor you write in
vscode, vs, rider, etc
when you dont know something search it
now you know 💫
nav should i use a ai for my bosses or should i just write it myself
its very Important to have a configured IDE if you plan on doing any work in unity, or anywhere else really
You write it yourself so if something breaks you know how to fix it instead of using regurgitated code that wont work 80% of the time
thx boss
oh, it was my fault, i forgot that the turtle snaps to the middle when it stops moving, i added an isDead bool
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);"
hop in vc
i wanna see
hehe
there is no vc in this serv lol
there is no vc here and lets not try get people in dms
i can make a vid
is there a code question here , this is kind of a code channel
you add suffix f to decimals to make them float btw. no need for this cast
are abstract classes the best way to make a weapon sys?
there is never a "best way" in development . every approach has its own pros and cons
i seee
what are the pros and cons of abs classes then?
compared with what?
harcoding weapons
your question is too vague
what does "hardcoding weapons" look like?
This is all way too vaguew
are you sure its colliding with the correct collider, maybe the portal has a extra component which is making it detect early
come back with some concrete ideas and code samples and then we can compare them
look into Interfaces as well, they can also provide good modularity without the constraint of inheritance
The phrase "weapon system" itself is extremely vague. That means something completely different depending on the game
if ur adding by the int u can just detect whenever the turtle meets a certain pos instead of using collision detection
The weapon system in Zelda Breath of the Wild is very different from the weapon system in Armored Core, for example
there is the portal platform and the portal as a child component, the portal can be activated or deactivated based on if a pressureplate is active, the teleportation code is all in the portal
when inactive the portal is disabled, the platforms is there so the player knows where the portals are
what platforms?
the only thing the platform has is a sprite renderer
give it a child object called "porta" then SetActive(bool)
why not just set those when it changes, instead of doing it each frame?>
btw you can just do BoxCollider.enabled = active etc.
if (active)
portal.SetActive(true);
if (!active)
portal.SetActive(false);
portal.SetActive(active);
thanks
but yeah don't need to do it every frame
You can change the image of the sprite, activate a child GameObject (with the portal image), or enable a SpriteRenderer on a child GameObject when it's active . . .
the pressure plate code activates is on trigger, how could i?
share the code
put the code in the ontrigger
wherever you are doing active = true; or active = false
you do it there
make a function instead of using a simple variable like that
or make a property
yeah mean doing this portal.SetActive(active); there right
Maybe - if that's what you're replacing those things with. It would be more maintainable to make a function or property that does everything that needs doing, so you only have one place where that would need to change in the future.
how do i share is in the dark box?
!code 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A tool for sharing your source code with the world!
llots of unecessary code duplication there
it broke the pressure plate code
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^
right, i could do it as a void active and inactive, did it recently with the player script and the movement code
oh, i didn´t even know i could do it like that, thanks
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!
void OnCollision(Collision Collider)
{
//save possition
}
cant u just do this
You're asking for the contact points, not the position of the object.
Have you checked the Collision object that OnCollisionEnter gives you?
i forgot the on collision thing tho
this is in collision enter
let me look into that
that is what I am using, c is the contact point:
private void OnCollisionEnter(Collision col)
{
foreach (var c in col.contacts)
{
var cPos = c.point;
putting the teleportation code on the platform, with a smaller boxcollider still gave the same problem
I can send a link to these lines in the repo if that'd help for context
yep that's correct, that will give you the actual contact points, not the center of the object
yes, I am aware of that.
however, i need to figure out for how much the object has moved because I want to apply a different force to each chunk(I use a fragmenter) based on how far away it is from the collision point
How far it has moved since when?
What are you trying to accomplish here?
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
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.
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?
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.
I am in Unity 6.3 and it's still there
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
thanks, google said it was in the General tab with a check box
we could be referring to a different thing tho
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
thats pretty much the only thing you can disable for scripts
the playbutton domain reload but thats only for playmode
there's also this
now that I looked again it says (check the asset pipline on newer versions...)
Thanks for all the resources, I'll look into it!
isActive is giving me an error
read the error
i tried to figure it out
oh
looks like you made isActive a float instead of a bool
i made it a public float
yeah that's why
why would it be a float?
the code you showed had it as a float
do you understand how ternary works?
the cdoe I showed doesn't declare the variable at all
no? it's checking if the bool isActive is true or not
making it a bool gives more errors
what??
WHy are you changing that code
no, sorry
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
well no shit you are changing the wrong thing
you said that i made it a float instead of a bool
keep change as a float, change isActive back to being a bool
yes, and you did
but you are looking at the wrong code
you changed your other code for no reason
no they said to change isActive to a bool not change "change"
oh, ok, 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
ok, it should be good now
but isActive has to be a bool for that to work
the portals don´t activate now, and the switch just gets darker and darker
what's calling UpdateSwitchState()?
onTriggerEnter2D
there should probably be an if (isActive == switchActive) return; at the start of UpdateSwitchState tbh
nothing else?
share the code saying this doesnt help me get any idea
yeah this is wrong actually:
// Assign switchActive directly based on the collision tag
switchActive = (collision.CompareTag("Player") || collision.CompareTag("Boulder"));
UpdateSwitchState(switchActive);```
i´m just using this code
https://paste.mod.gg/lhwlgwguljyh/1
A tool for sharing your source code with the world!
this is outdated unless you went back
if should be like:
// Assign switchActive directly based on the collision tag
if (collision.CompareTag("Player") || collision.CompareTag("Boulder")) {
switchActive = !isActive;
}
UpdateSwitchState(switchActive);```
still nothing
you mean
if (collision.CompareTag("Player") || collision.CompareTag("Boulder")) {
switchActive = !switchActive;
}
UpdateSwitchState(switchActive);
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
yeah the fact it's two different variables is basically wrong
it needs to be:
if (switchActive == isActive) return;
isActive = switchActive;
// the rest
switchActive would be better named newActiveState or something
it works now
you have 2 bools trying to do the same thing but never equal each other delete the isActive and do what i put here
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
how can i make it detect it like this?
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
Where is the object that has the MagicBoltScript that you're trying to drag into, and where is the object that has the ExtendedCharacterController?
Is one of them in the scene and one is a prefab in the project window? Which is which?
Also right now your private ExtendedCharacterController extendedPlayerController; field is NOT serialized so it shouldn't be showing in the inspector regardless.
another point - your extendedPlayerController.GetComponent<ExtendedCharacterController>(); line of code in Start() is completely pointless and does nothing
the object that has the magic bolt script is a prefab variant object
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
yeah that's your problem
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
oh lol I fixed it, I passed it the player prefab instead of the player in the scene
but that won't work at runtime then
it did tho
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.
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
public void FixedUpdate()
{
transform.position -= transform.up * Speed * Time.deltaTime;
//Debug.Log(transform.forward);
}
Your original premise that you needed the reference to get the position was inaccurate
you're just using it to get the magicMissileDamageMultiplier
oh right, in another script I have it following the hand transform
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
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);
Again it will only not work if that value changes on the player during the game
if magicMissileDamageMultiplier never changes, then it's fine, if a little weird
well it works for now so yay
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.
I'll try to obey the rule but it's a habit that I type like that sometimes. I'll have to be actively aware of my typing behaviour. What a drag.
this looks like something for jobs you didn't mess with stuff in preferences did you?
Not as far as I can remember, I've been dealing with it for months now, just got annoyed enough today to come to the discord lol. I believe it happened after upgrading at one point.
upgrading versions or licensing?
Versions
Yeah, not spamming a channel is a requirement. What nonsense /s
Know of a way to restore all default preferences?
i dont sorry
wait you wouldn't happen to have Show Timing enabled would you?
at least im pretty sure that's what it is based off this response to someones post https://discussions.unity.com/t/profiling-burst-compilation-times/937302/6
Hi guys! I have a question about some basic code, how can i paste the code like this message? To have this format so you can read it better
just type 3 of these ` at the beginning and 3 at the end
how can i check if someone is from mobile phone or desktop in webgl game
does anybody know how I'd do this in the new input system..?
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.
thanks i'll take a look
{
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...
oh that's for like per-script movememnt I use this
a player input component
and a input manager script
shouldn't use delta time for AddForce as far as i know
The usual solution is to tweak either the friction of the ground and/or drag of the player rigidbody
also you using ai for this?
make sure to put cs (```cs) at the start of your code blocks. makes it a little easier for us to read.
i have no clue how to translate key down and get key to this
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
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
not a code question, although you should just be able to import it and then set the pixels per-unit to whatever it's supposed to be
Can you tell me an example or where can I found some resources to look at it please?
oh my bad i thought this was unity beginner
Should I? Probably not, right?
no just thought you were cause the comments seemed like the ones ai would write
I'm not sure what kind of example you're looking for. Change the values and see what happens
I feel that I'm not understanding well the physics and I don't know where to look
but as this answer says Time.DeltaTime shouldn't be used https://discussions.unity.com/t/does-addforce-use-time-deltatime-or-time-fixeddeltatime-or-it-depends-on-whether-it-is-being-used-in-update-or-fixedupdate/237627/2
i could just change how i handle input for this one instance but that seems weird...
Oooh, I'm just trying to comment everything so I don't forget what I do, at least for the start
Tysm!!! I'll note it down for next time
fair im sure it's better than some of the messes i've written before like this one.
which isn't even half the function call yet it's only random if statements
check the documentation it has everything explained like Buttons and what not
Well, it happened to me tbh hahahaa
does the player input component give off a held value or smth?
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)
you configure it to either give you from the button a press or press and release
Note that this can be simplified, when you have conditions of the like:
if (x == 42)
val = true;
else
val = false;
You can shorten the whole thing to val = (x == 42);
yeah i understand that part im just struggling with....executing that in code
like how do i transfer
really?
the getkey and getkeydown stuff to this way of input
wdym how to transfer it ? use a bool
like how do i tell if the button is being held or just pressed like how grt key and get key down did
set it as button mode and you get 1 frame event was it was performed
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.
could you write an example? I apolagize if I seem dense but I'm just not comprehending 😭
not at the pc right now but you can for now replace it with this until you learn more about it Keyboard.current.rKey.wasPressedThisFrame and its a direct to GetKeyDown R.
this is the input format i use
so do the same thing ?
so like Value.wasPressedthisframe?
you don't really need that if you do the SendMessages with action map as you did with OnSlide
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```
the tutorial I'm watching sets a shooting variable instead of callinfg a function
as I said before you can also use a bool field to store the state of the action
alright hopefully this works
thanks
there are tons of ways to use this input system btw
as you might tell lol
ik i usually work in godot so this seems so much more complicated 😭
it seems so because this is a swiss army knife, the old input system was more like a butter knife
in godot you just do this and call if input.isactionjustpressed("input")
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
yeah i've played with unity for awhile i always just hated the input system and never learned it properly out of pure spite
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
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
so your physics query i s not catching anything
you can do dozens of these especially with nonalloc and be fine
nothing to do with that
i resize it and ends up for the int is not zero now works
if it was a problem a lot of games wouldn't exist lol we'd be playing pong
but the last one doesnt
{
PlayerGunSystem.Shooting = true;
} ```
is this what you mean?
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
ok
if you want to use a bool instead of directly just calling the method.. not like this . you need it to set to false somehow or you're "stuck" in that action
but the weird part is, it should
all of em inherit from it
idk what you mean "all of em inherit from it " but "should" is always based on assumptions.. never facts, use facts my checking over the values
see which colliders are catching and what components those have
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
what i want to do is if your allowed to hold then it sets shooting to true every frame that the shoot button is pressed but if your not it sets it to true then false the next frame
but is component on the same object as the collider?
Debug.Log hitDemons [i].name
holup
make sure ig
whats 3D got to do with it lol the code is exactly the same
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
TryGetComponent only looks for the components on the collider object not Parents
rigidbody shouldn't affect that
i changed opinion
the spherecast works
so it should work
my internet is trash
Y E A H
but im completely stuck
are you talking about
Hold to shoot and let go not shoot ?
mhm
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
the allowbuttonhold is basically auto or not auto
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
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.
I didn't say anything about spamming.
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
what are you actually trying to do?
you could probably use the package manager api to find out if the packages exist
this you can probably do with Interactions enum
what's that?
presumably a enum named Interactions
Let's not make it sound like a special enum then.
your right lets call the enum Pizza
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.
hmmm. Tbh I could do that. tbh its a bit annoying and very domain specific to describe. basically, generation of 'proxy colliders' at build time for the component you lack, and the intent is to feed it a list of either DB or MC2 colliders
can I not add gameObjs in the scene to prefabs?
assets (such as prefabs) cannot reference objects in scenes, if that's what you mean by "adding"
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?
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.
nah, it's just scene objects that can't be referenced. Assets can reference other assets just fine.
I'm trying to have an onclickevent to basically tell the deck editor to add 1 copy of a card to the decklist
actually its a class
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/api/UnityEngine.InputSystem.Interactions.html
but yeah you probably want to research more on this, last time I think I did something like context.interaction is TapInteraction or context.interaction is SlowTapInteraction
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Interactions.html
You'd have to have the prefab in the hierarchy and you can temporarily set a reference with a SerializeField.
Most likely the singleton pattern is your simplest answer here
Would using an Event and subscribing work here?
like creating an instance of the script to be globally referenced?
The "deck editor" presumably there's only one of those right? You can make it a singleton
then you have a static accessor property to get the reference
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?
As long as you only try to access it when it exists
ah, then good
you could also have the card fire an event and have something in the scene subscribe to it when you spawn the card
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?
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.
like its honestly very easy to detect MC2; it defines a symbol in the project, MAGICACLOTH2
you can pass a reference to itself while invoking the event
you can do whatever you want in your code
I can't do whatever I want because c# will tell me "no you can't do that"
I can try for sure
well when you understand C# you can do whatever you want
Oh, btw with that singleton example you can type SingletonExample.Instance.MethodExample() or SingletonExample.Instance.variable if you make them public.
could you also just use something like this?
https://discussions.unity.com/t/detect-if-a-package-is-installed/838614/2
you shouldnt need a symbol specifically for this
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
oh I guess it does change if you're trying to reference the specific components
But, generally the singleton pattern tends to be avoided except in certain situations. creating an Event and subscribing to it is the cleaner method.
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?
🤔 singleton and events solve entirely different problems. An event would live on an instance (unless for some reason you make it static)
Singletons are very common
events would be better then since these will be instances made from prefabs
You're adding that method to the event to be called when the event is fired off.
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
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
event seems like the optimal solution
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?
Oh, and usually it's a good idea to subscribe OnEnable and unsubscribe (-=) OnDisable.
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
un sub in OnDestroy() if done in a monobehaviour
because it wont magically un sub itself!
now I need to tell each card to "tell deckeditor to add a copy of yourself to the currect deck"
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
Where would I create this new event? In deckeditor?
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
So a new event e(this) and then CardUI.button += event e?
basically:
CardUI newCardUi = Instantiate(cardUiPrefab);
newCardUi.myEvent += MyEventListener;```
And when it gets destroyed you need to `-= MeEventListener` on that same instance
so OnDestroy I need to unsub
This way round its not essential to unsub as we can presume CardUI wont invoke its event any more after being destroyed...
You should make the cards scriptableobjects if you haven’t.
do not worry I have
true actually, if the button's lifecycle is less than the deck manager, you don't need to unsub
this doesnt make a lot of sense, what is a deck? why are you adding a copy?
I assume you meant you want to pass a reference of DeckEditor to the Deck
Is there a way you can share the project so we can look at it? Edit: Don’t do this.
you do not need to share the project, and shouldnt either. I am asking specific questions about the design
ah
Fair enough. Noted for next time.
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"
Essentially, in the DeckEditor scene, the player should be able to:
- 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
- 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.
- 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?
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
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?
You can use quaternions to rotate a vector
I was messing with that but with no success
Quaternion.AngleAxis
Quaternion.eulerAngles is easiest to work with.
Something like Quaternion.Euler(0, 0, 45) * dir should work
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
Their description of the current deck editor design is fine
using singletons here would be dumb and im glad they arent
I was thinking of reusing them for the actual main game, and just have the gameManager take care of OnSceneLoad and do a check to see if we're in main game or deck editor
and thus give it different logic based on the scene
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
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
that's basically my plan
Then its all good 👍
It basically says "i've been clicked" and the deckeditor/gamemanager handles the rest
public event Action<Card> OnClick; 🙂
I just need to figure out the event system so I don't screw everything up
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
some unique id or the data object works, programmers choice
so now my DeckEditor can listen for these events?
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
so I tell the DeckEditor to subscribe to the event of the instance
yea
CardView card = Instantiate(cardViewPrefab);
card.Init(cardData);
card.OnClick += OnCardClicked;
its just as praetor wrote here #💻┃code-beginner message
Quaternion thing = Quaternion.Euler(0, 0, 90f);
direction *= new Vector2(thing.x, thing.y);
Direction is being set to zero
I have zero experience with Quaternions
wtf are you doing 😆
you are reading x and y of a Quaternion this wont do anything useful
How am I going to use that rotation then?
I don't understand
thats not similar to what they wrote even 🤔 you dont read the individual components of a quaternion. you use the multiplication operator
https://docs.unity3d.com/ScriptReference/Quaternion-operator_multiply.html
look at 2nd declaration
I never worked with Quaternions before
Vector2 rotatedVector = Quaternion.Euler(0, 0, 45) * new Vector2(0f, 1f)
this operator use is documented here: https://docs.unity3d.com/ScriptReference/Quaternion-operator_multiply.html
Ah, I was using the *= operator and Unity was complaining
Thats why I was reading the components
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
It worked guys, thanks for the help
I gave such a clear example 😭
yea you arent calling the function, just using it in the event sub
its like when we do nameof(MyCoolFunction)
ahh
what is this used for?
how do I mass unsubscribe from the instances? Do I do a foreach or is there a quicker option?
string name = nameof(MonoBehaviour);
produces a string of the symbols name
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
symbols name?
ahh makes sense, never really used it since i don't like either Invoke or Coroutines
"Symbol" being the generic term for fields, properties, methods, classes, etc.
Things that show up in blue in VS
unless Log for Debug.Log is meant to be one of these Symbols i think i have the wrong blue
If you store a list of all the cards then you could unsubscribe by going through the list. If the deck editor is only destroyed when the whole scene is then you dont really need to unsubscribe here
ah, then good, because yeah it is destroyed on scene change
Log is a method. That method name is a symbol.
Fair i guess i knew that was more so getting at how nothing else was blue :/
as a warning for the future, you can only unsub from an event using the same function on the same instance
so if you subscribe with a lambda you need a reference to the same one to unsub it later.
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
Holy cow, yes it was enabled- thanks! lol
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.
do I need to assign the OnClick event to the button component?
I don't think the OnClick is firing
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
it is, thanks
event?.Invoke() this lets us invoke the event and avoid a null ref exception if it has 0 subscribers
otherwise you can do event()
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?
What’s the difference between Euler and eulerAngle?
select your scene's EventSystem and you can look at its preview window to see what is being detected by it. that will tell you if something is blocking a UI object
how do I select the eventsystem?
Euler was a swiss mathematician.
eulerAngle - you'll have to be more specific
Quaternion.Euler is a static method that creates a Quaternion from Euler angles. Quaternion.eulerAngles is an instance property that provides a Vector3 containing the euler angles derived from that quaternion
I always found eulerAngles worked for me. Quaternion is difficult for me to understand.
with your mouse
yeah but like where? It's not in the heirarchy
then you don't have one
well then that is precisely why your button isn't working
EventSystem is created when you create a canvas, yeah?
you probably deleted it by accident. or you created the canvas manually rather than through the Create menu
Or copied your UI elements from another scene
or that, yeah
Can you safely child the EventSystem to the canvas game object for the purpose of prefabbing?
Depends
I wouldn't recommend it generally
It's very common to have more than one canvas in a scene
And you only need one EventSystem?
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
What do you mean by "i want the trigger to check it instead"?
Do you have a nifty link that explain how the EventSystem can be modified or is that not necessary?
You can use OnTriggerENter on either object involved
oh you can? that's exactly what i wanted
thanks
I could probably google it but if you know something that’s very concise that would be very much appreciated. 🙂
what modifications are you talking about
Eyy I did it and it added to the decklist
Just understanding what you can do with EventSystem.
You can write custom input modules and custom raycasters
there's not much you can do with the EventSystem directly
Ah ok, fair enough. Thank you.
What would be the purpose of custom scripts? What would that achieve?
Modules and raycasters sorry.
Awesome, thank you. 🙏
unity UI 3.0.0?
wanna explain what this means for the uninformed :?
that's just the version number for the UI package
I have no idea what you're asking to be honest
so is it independent from the unity version?
yes, it has been for a couple of years now (assuming you mean the UI package being separate from the engine core)
All packages have their own independent versions from the Unity version, yes.
yeah sorry i was just curious cause i'd never heard of it and thought it was a seperate app to develop UI's
What’s the new UI system called? Looks really customisable?
UItoolkit
note that what praetor linked is just the regular Unity UI package, not UITK and is not new.
is it any good, compared to just using TextMeshPro / unity's normal editor?
I've only used for Editor
It’s amazingly customisable but you need to know css and stuff.
unfortunately still missing a few features that ugui supports though, like shader support
yeah still doesn't feel 100 there yet..didnt they only recently put world canvas or somethin
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
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
did they fix the z-order in uitk already?
There's nothing to fix, if you are asking if custom z-index is a thing, then no
ah so no z-order still.. sad face
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
then no problems? just a visual bug?
is there anything wrong?
not a code question. although other than it being disabled, no
Could you even disable transform..?
wait your not allowed too?
no, not sure how they did
am i gonna get banned
I thought it was physically not possible.
my friends keep saying its wrong?
No, but maybe provide a better explanation/question.
photoshop is my guess
guys why isn't my cube responding to the "invoke" function and the game just restart instantly?
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.
how so?
i set a value of 1 sec for the invoke
but also how did i call it early in the code?
yeah but that happens after the function Restart() is called
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).
well i just flipped them but nothing got fixed
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?
well then how do like make them seperatly?
i still can't like form a proper code by myself yk
i just started learning
just remove the Restart(); line
the invoke function
When you use Invoke it calls the function you typed in there, after the amouint of time you specified. That's its purpose.
thats what it's there for cause unlike coroutine or async / await it doesn't pause that function from continuing
yep it worked
Imagine telling your friend to come help with something then immediately telling him to come help in 5 minutes
If your trying to learn there’s never a need to apologise 😄
well only if you are actively trying there's some (realistically most) that just ignore what you tell them cause it isn't what they want
imo its pretty easy to tell if someone is trying to understand what their being told
i will try from now on to like read the code and understand it
I been blessed by the coding gods because unity decided to not give me a error in the last 10 minutes
im with u on this
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.
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.
Also, I'd like to recommend this documentation for you regarding something else you might find interesting.
https://learn.unity.com/tutorial/introduction-to-object-pooling
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
how do I actually get the position of that object specifically though?
cuz like rn I'm just using the players position since the script is technically a child of it
A tool for sharing your source code with the world!
What is PlayerSpells attached to?
have a serialized field of type Transform and assign that as an anchor
[SerializeField] private Transform weaponSpawn;
Then go back to unity and drag and drop the weaponSpawn gameobject in the new field for PlayerSpells.cs.