#💻┃code-beginner
1 messages · Page 517 of 1
I'd like to see a game engine without a garbage collector or a similar system.
But this probablt involves at least an O(n) time complexity, alongside other factors that consume unnecessarily
The audience it would reach may not be as high as planned because fewer people know how to do proper memory management
It would be addressed to advanced programmers, or even studios
Which in terms mean they would need to charge a lot of money for it to be sustainable
It's not as much about "knowing" how to manage memory. Some complex systems simply can't function without sort of a garbage collector.
people actually destroy their objects?
I agree, it would be great to have an option to fully manage memory
Biggest problem for unity is that GC isnt generational
One nice thing about cargabe collector is that the workload can be divided between multiple frames which unitys garbage collector does so you don't need to worry that much about performance even if you dispose of large amount of data at once
Even more important, the vast majority of programmers are totally incompetent and so systems like garbage collection are a requirement to protect their users from crappy code
I've got a few scenes that are identical except for the types of enemy waves that are spawned. I know I can have all this data be in one scene but I'm not sure what method to use. For this type of data loading, would that be done with scriptable objects?
yes, that is exactly what you should be using
relative to what? surely not relative to *heap size?
relative to the amount of objects in the heap would sound reasonable though
Hi everyone! I’m a beginner working with prefabs, and I’m running into some issues with maintaining references in my Unity project. I have a car prefab that I spawn at runtime, and it needs to be assigned to the camera, but the reference to the car is lost every time I spawn it. Right now, I’m using FindObjectWithTag in Update() to re-assign it to the camera, but I know this might not be the best approach. The car also has button references for touchscreen movement (forward and backward), and because it’s a prefab, these references in the inspector are empty. I know I could assign them with a script, but it seems like it could get overly complex. Is there a recommended way to handle these references efficiently without a large script? Thanks!
FindObjectWithTag in Update is not good. You have to assign it when you spawn it
whatever is in the scene already had reference to camera, when you spawn you pass the reference
What you mean by reference getting lost on spawn? Instantiate returns the instantiated object, why not use that?
he means references on the script that is on the instantiated object i think
In your code block where you have Instantiate(prefab,location,rotation)
Make it GameObject newReference = Instantiate(prefab,location,rotation)
Then where ever you need that reference for your game you just use
NeedReference = newReference.
Doesn't sounds like that's what they mean
Let me explain like this, for example, there are ui buttons which i use to move the car forward ,backward , left and right. All these buttons are assigned to player movement script which is on the car. As i am making a multiplayer game, i need to make prefab of this car and spawn it when player starts the match. So i made a prefab of this car . And when the match starts and the car spawns, all the buttons which i assigned are going away, like its showing none in the inspector. I dont want them gone...
pass the reference when the object is spawned https://unity.huh.how/references/simple-dependency-injection
. As i am making a multiplayer game
oh lord..sure hope you mean same screen multiplayer..
Its online multiplayer
You should probably not start with that
you should def not be making multiplayer lol
I already made all the physics and stuff dude
yeah but that's physics
should prob know to even pas references at very least..
hey its your game. Just not something you will probably not finish but hey, best of luck
you are trying to go into the deep end without even knowing the fundamentals of C#
I mean i already know how to do it but chat gpt says its inefficient
chat gpt 
I lie on the internet in hopes that chatgpt copies that lie and spews it out to someone
😨
one of the engineers at OpenAI "accidentally" training the bot from messages on the Unity or GP server 
"How did the bot steer us wrong, we trained it on decades of StackOverflow data!"
"The answers or the questions?"
Hi, can someone help me why I can't see the list in Inspecotr?
please ping afterwards
you need [System.Serializable] attribute on the struct
it's [SerializeField] , not [Serialize] - though it's not needed for public fields
Because Emails is not serializable
Only serializable types can be serialized.
Refer to https://docs.unity3d.com/6000.0/Documentation/Manual/script-serialization-rules.html if you're not sure what is and isn't serializable.
Primitive data types (int, float, double, bool, string, etc.)
Enum types (32 bits or smaller)
Fixed-size buffers
Unity built-in types, for example, Vector2, Vector3, Rect, Matrix4x4, Color, AnimationCurve
Custom structs with the Serializable attribute
References to objects that derive from UnityEngine.Object
Custom classes with the Serializable attribute. (Refer to Serialization of custom classes).
An array of a field type mentioned above
A List<T> of a field type mentioned above
Okay thanks
Ya also don't need to initialize it with new
in modern C# you can use a primary constructor and do List<Emails> everyEmail = []
but not in unity. also that's not a primary constructor, that's a collection expression
List<Emails> everyEmail = new(); works just fine
or in this case, no constructor call is needed as Mao pointed out since the list is serialized by unity so an instance is automatically created
man I made so much fun at c# about the syntax of the full initialization, then the next week they released the version for the short version
was like 2015 or something? Surprised it took them that long
I meant primary constructor, and a collection expression. I just realised that unity doesn't really adopt .NET 8 :P
of course if you wanted to downcast it you would have to type out the full syntax of it
syntactic sugar, there are so many other, important, things that the devs could be concentrating their energies on
how is a primary constructor relevant here? 🤔 are you perhaps confusing target typed new with a primary constructor?
Guys i got the multiplayer working with photon fusion. Everything is working well. But the car movement is not smooth. Its a bit jittery. Can anyone please tell me how to fix it. Thanks in advance
#archived-networking
also photon has its own server you can ask for help with their networking tools in
and networking is not for beginners. you will fail if you don't actually understand what you are doing
I followed their guide to make the player movement smooth but it isn't working. Guess I'll have to post this on networking
you would be better off asking in the actual photon server. and post actual details
is there a way in code to do the equivalent of alt + clicking the bottom left corner?
you know the long notes in rythm games where you have to hold down on it and the bar is erased as you hold
wouldnt that be x anchor 0, y = 1
what's odd is when I click alt + bottom left, it doesn't change the anchor values
is it bad that im doing it by having lots of tiny gameobjects destroy
don't crosspost, if someone knows they will help #💻┃unity-talk
if you keep destroying and creating, consider using pooling. It will save you ton of garbage production
this is not a code question. and don't crosspost
you've already asked for help in #💻┃unity-talk . keep the question there. and delete it from here
how you been on in 4 months if latest unity dropped oct 17?
beta my dude
if it wasn't working since preview/ beta the issue is somewhere with your PC / config
i see it "could be" but i see no reason for it not working out of the box
i didn't do any weird configs or anything it's just a standard win11 install
sorry for posting twice it's just driving me crazy i can't create a hdrp project at all or add any library that uses com.unity.settings-manager
for 4 month or more now
the objects are pre placed in the scene rather than instantiated
so what happens when you destroy them? you don't spawn them again ?
dont spawn them in again
so then what is your question about ? It doesn't make sense to ask if its okay to destroy
why would be issue destroying
thinking it may be laggy to destroy 200-500 ish objects in a short period
are you just assuming that or you actually tested this
when you set to Destroy it doesn't even do it right away, it waits till the GC is coming to collect
DestroyImmediate is a solution, but not recommended
thats meant for assets not instances
but in the docs, it has a second parameter called "allowDestroyAssets"
idk I only used it in the Editor which from what i know , should only be used in that context
like destroying maybe TEMP objects created in Editor
idk what the bool is for tbh my assumption is was for that by default
hey, where'd the question go? i was reading . . .
Unfortunately no, I was gonna reformat but here it is.
Hello. I'm trying to display a crosshair and item name when my raycast hits a 3D object. I'm using a UI Image and a TMP_Text. Pretty much everything I have that's relevant has been up in the video below.
The Bug: When I look at an interactable object for the first time and my HUD displays, there is a jitter or jump in the camera. It only happens the first time the TMP_Text is drawn on the HUD.
Note: Sometimes the jitter or jump is larger than other times. Sorry if the issue seems super obvious, please pardon my incompetence. Also, in the video I had no idea why it was happening but have since figured out it's related to making the TMP_Text visible for the first time.
Video: https://www.youtube.com/watch?v=YulfGxssvJ8
PlayerInteraction.cs: https://pastebin.com/gyeYX9eR
Interactable.cs: https://pastebin.com/aJYh3kgM
Info & what I've found:
If it matters my player's movement is done in FixedUpdate() while my input is handled in Update().
I tried changing the PlayerInteraction for CheckForInteractable() to FixedUpdate but that did nothing, so I reverted it back to Update().
It's specifically when the line 48 of the 'PlayerInteraction.cs' runs. Why drawing the TMP_Text for the first time is causing a stutter? I have no idea and I'm not sure where to continue this debugging process. I confirmed it doesn't do this by commenting this line out which seems to fix the problem. There may still be a tiny stutter without it, but if so it's nearly unnoticeable. Could just be placebo for me looking for a stutter.
interesting. only thing i can see it being is enabling it, though, that shouldn't be a problem. try placing a CanvasGroup component on the text GameObject and instead of enabling the interactText variable, create a canvasGroup variable and set its alpha property . . .
Hello, guys! So, I would like to know if there is a method in Unity that loops a clip infinitely. What I mean is that I don't want the clip to reset at the end in the loop of the clip but to infinitely being played over and over? I don't mean that loop because that checkbox is resetting the clip at the end of it's duration.
When the player dies a scene should load with a username text promting user to input a name. but should also be able to press play or quit too. this menu should looks the same as the startmenu except the text input thing. Is it better to have two different scences for that or have a deactivated element in the startscene and use same scene for gameover scene but with a logic saying if <player has died in gamescence> activate this gameObject. Which is the best?
I'll have to do a bit of reading real quick to actually figure out how to do this but it makes sense in theory and I'll get back as soon as I figure it out on if it fixes the stutter or not. Thanks for taking the time to read and reply.
Does anyone know what are the names of the CONTEXT menu elements for every component? Like rectTransform in this case.
If there is a full list somewhere it would be great tho, but for know I only need to know how is the inputMap assets from the inputManager package called.
[MenuItem("CONTEXT/RectTransform/Action", priority = 1)]
!blender
A supportive community for Blender artists of all levels. Share your work, ask for help, and learn from others! https://discord.com/invite/blender
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
np, it won't take too long . . .
- add CanvasGroup component to text GameObject
- add
canvasGroupvariable toPlayerInteractionscript - assign the
canvasGroupvariable from the inspector (same GameObject as the text) - comment out
interactText.enabled = true; - set
canvasGroup.alphato 1 (to make it visible)
Hello, I'm just now starting to use Unity to make my first ever game, and I was wondering if anyone here could show me how I could add a border to my 2D game? Currently, if I set the RigidBody 2D's Gravity Scale to anything over 0, the character just falls from the map. so I would like to add borders so that I can add gravity to my game.
box collider 2d components would be the simplest
I have already add a box collider 2d component, but could you please explain to me how I could use it to set a border?
you would just arrange them to be at the bounds of what ur camera is seeing..
and so on..
Ah, got it
Could somebody explain to me how exactly I should set the box collider where the character wouldn't "hang" onto it, but instead just step on it?
np, it won't take too long . . .
main character looks like its collider doesn't match its shape..
looks like it only has a collider on its head
is there a simple coroutine class with OnCompleted callback in unity?
i want to have a list of coroutines and maybe end them before they finish
no, you have to create your own . . .
you could probably make a custom class to handle it
ye just asking quickly
or pass in a callback, or check a bool variable that can change outside of the coroutine . . .
var myCoroutine = coroutineHandle.StartTrackedCoroutine(MyRoutine(),
onCompleted: () => Debug.Log("Routine Completed!"),
onCanceled: () => Debug.Log("Routine Canceled!"));```
thanks both of u
good luck.. would be a cool helper class to keep for later
Bump
if those are both 2D colliders it shouldnt be doing what ur video shows it do
unless ur movement code is bad..
that's how i ended up creating a timer class with a bunch of actions, like: onCompleted, onCancelled, onSuspended, onResumed, onUpdated, onRestarted . . .
using UnityEngine;
public class MainCharacter : MonoBehaviour
{
public FixedJoystick joystick;
public float moveSpeed;
float hInput;
void Start()
{
}
void Update()
{
}
void FixedUpdate()
{
hInput = joystick.Horizontal * moveSpeed;
transform.Translate(hInput, 0, 0);
}
}
This is my movement code (I haven't added vertical functionality as I'll be adding a jump button)[
solid.. i wish i could think that far ahead 😄
public TrackedCoroutine(MonoBehaviour owner, IEnumerator routine, Action onCompleted, Action onCanceled)
{
this.owner = owner;
this.routine = routine;
this.onCompleted = onCompleted;
this.onCanceled = onCanceled;
}``` something like this eh?
this is ur problem.. translation/teleportation (just moving the transform) doesn't respect physics
given enough transformation it can literally clip/ phase right thru ur collider
must use Rigidbody2D and accurate physics functions (for the best collision detection)
Could you recommend me a guide for that?
This tutorial goes over all the different options for moving a player in Unity and the benefits and disadvantages of each. It also goes over the difference between Rigidbody vs Transform movements. If you want to take a deep dive on how to do movement in Unity than this is the video for you!
Patreon:
https://www.patreon.com/gameGLiTcHsupport
S...
gloss over this.. should show u some new stuff that u can then search more about
Sounds good, thank you very much for the help!
https://www.youtube.com/watch?v=3sWTzMsmdx8&ab_channel=Tarodev i use this as a base for my 2d controllers
I'll take a look at both and see what'd be easier to implement into my current code. Thank you very much! ❤️
I will be making a dev beginner server if anyone is interested, dm me
this is not the place to advertise your server
#📖┃code-of-conduct
yeah, that's pretty similar. smart to add the MonoBehaviour. i have a constructor that binds to a MonoBehaviour just in case it's important if the object remains alive/active. is the time (for the coroutine embedded in the routine parameter or do you pass that as well?
i just figure if ur dealing with coroutines its best to go ahead and have a reference to the mono
tbh its a work in progress.. i haven't actually began using it yet.. but its been on my mind for a while..
since the other guy brought it up i figure i might try to implement it today
do it. you'll be surprised how quickly it turns into its own package. probably the coolest project i've done . . .
can someone teach me c# i beg😭
lol.. thats why im tip-toeing.. its on the fringe of my understanding Lmao
the monobehaviour / coroutine relationship makes it pretty difficult in my eyes
i could build it... but do i completely understand it..
^ thats the dilemma
that's the truth. it's best to isolate/work on it in a separate project. then you won't have any other distractions. just make a simple coroutine that counts to 10 every second or display a log after a certain time. then you can mess with the calling onComplete to check that it finished, onCancelled if it was cancelled manually, etc . . .
break a feature down into task, and complete each step at a time . . .
good approach.. thanky
i'll give it a shot
learning experiene if anything
that's why i attempted to create my own pooling system, so i can understand how they work and to be able to add custom features. of course, this was before unity decided to make their own, but it's good practice . . .
ya, imma try.. if anything its events, actions, callbacks
all that stuff that im a bit uneasy about
that's the part of practicing most people don't do. it's hard to learn something (a concept) if you don't attempt it yourself . . .
the easy thing to note is that all of those words are synonymous with each other. they're all delegates, just called different names based on their use . . .
bro how do i edit keyframes when im in edit mode it just makes new keyframes and when im not in edit mode it just doesnt save the changes 🔮
this is a code channel
is that the easiest thing to do?
to me its more complicated b/c of how similar they all are
Idk if its just selective bias but I suddenly see many people using [field: SerializeField] instead of just [SerializeField], is there any difference or just syntax sugar?
im 100% sure theres a difference in the two.. (soo more than just syntax sugar) specifcally? idk yet
i think [SerializeField] is unity specific... and the other one is not.. and can be used to serilize backing fields of auto-implemented properties
backing fields? no clue lol but yea..
theres ya go.. thast the difference
field:SerializeField is how you serialize an anonymous backing field
oh, so it makes it work for properties?
So basically what rider calls auto-property? 😄
Yes, because that's what they're called
aight, ty
[SerializeField]for private fields you want to edit in the Inspector[field: SerializeField]for auto-properties when you need Inspector visibility with encapsulated access
a sprinkle of complication
allows you serialize auto properties
such that you can make it a private setter, public getter
unity has a lot of attributes, so it's nice that it's still the same attribute name
ye, and for all attributes if it's being applied to the auto property field you need to continue to use [field: ...] on it all
[field: Header("Settings")]```
Hi, how can i get vector with this direction?
basically backwards from your plane?
property fields are useful when you want a simple listener for when the property has changed
Yes
-transform.up
-transform.up, -transform.forward
or -transform.right
depending on how its oriented
Is this a good way to check if player is holding mouse over a location in a grid in unity ?
When the mouse is clicked, see which square in the grid its in and keep checking if its still inside that square
And have a coroutine to have a hold timer.
I just checked out the hold interaction using the unity input system, however I need a way to be able to control how long the hold is depending on the type of object the mouse is hovering over.
sounds like rolling ur own solution would be best if it were gameobject dependent
not sure tbh
hmm, I wanted to do it this way because they are tiles in a grid
i'd ask around some more..
Does anyone have experience with GitHub I just overwrite my entire unity project trying to make a back up
How did you manage that
Did you delete any files, or use any sort of --hard git command?
Probably pulled instead of push
Still won't erase anything unless you --force it
Thankfully I had a zip backup on my email but all I did was create a new repository and it overwrote my entire unity file with just the gitignore left in it not sure how that happend
Creating a new repository won't do anything to files on your computer
Unless you specifically deleted the folder, or used --hard or --force or some other git command that requires specific intent
Yeah that’s what I don’t understand unless I somehow deleted it prior to creating the repository I just noticed it was empty when nothing got pushed
Sorry kind of new to GitHub don’t really understand it all yet
What did you actually do? Are you sure you're not just looking at the wrong folder?
Sorry, I was AFK. Here's an example of the difference between them (Pulled from StackOverflow) . . .
I just met you,
And this is crazy,
But here's my number (delegate),
So if something happens (event),
Call me, maybe (callback)?
No, not GameObject . . .
dose anyone have rescorce for this question or youtube video to understand the consept
i did the projctile and the movement and the animales but the game over thingy and the spawing idk how
Hey, question 🙂
Im using a script that reads out a spreadsheet, and i made a script where the data from the sheet (per row) gets put into a list,
is there a way for me to read out this element from the list into text?
so, lets say, the list has int ID + string NAME, how can i show that id + name in text ? cus i googled a bunch and cant really figure it out :/
What part of it are you struggling with?
You put the data into a list of what? Strings?
"the list has int ID - string NAME" that's pretty vague. You should share more details.
im sorry!
[CreateAssetMenu(fileName = "AppliesConfig", menuName = "Config/AppliesConfig")]
public class AppliesConfig : ScriptableObject{
public string sheetId;
public string gridId;
public List<AppliesConfigList> applies;
[ContextMenu("Sync")]
public void Sync(){
ReadGoogleSheets.FillData<AppliesConfigList>(sheetId, gridId, list => {
applies = list;
ReadGoogleSheets.SetDirty(this);
});
}
}
[Serializable]
public class AppliesConfigList{
public int ID;
public string Name;
public string Role;
public int Age;
public string Country;
public bool Bool1;
}
This basically
but now, i would like to get those things converted to text elements and such,
So i can change / look at them when i hit play
It’s probably easier then I think but I’m overthinking stuff I guess haha
Pretty sure they should be visible from the inspector but I'm guessing you're wanting the data in the scene?
im not sure which part of this are you struggling with either. your question seems like you just are asking how to get data from a list which you can do with a foreach or for loop and access it via applies[index]. this code is also quite complex compared to reading data from a list though which is basic c#
Make a ui object reference the scriptable object and simply populate the text/label. I'm unsure if you'll be able to change the asset:scriptable-object permenantly during runtime release but you could probably write/send the updated data back to the Google sheets ect.
You would need to create a UI prefab with all those different text elements and then just set the text property on them in your code from the objects in the list
(Instantiate one row per element in the list)
does anyone know why my code is like this https://paste.ofcode.org/39CRjaRQM9P5s2uEm53Agy4
Because you start the same coroutine within a coroutine. Which in turns starts another coroutine, etc...
memes allowed now?
anyways, item system help, I want to have an SO with item data, how do I store custom datas for different item types? like foods have a satiety property and weapons have attack speed and damage.. What's the best design here?
inheritance?
Inheritance is perfect for this type of deal
Although recently I have taken a liking to just using interfaces like IEdible for example
Setting a LayoutElement property indirectly though a custom editor. With a float input field. For some reason, it's not updating properly.
If i can't get any ideas to fix it. I'm thinking of just create a task that calls SetDirty through reflection each gui frame for x times.
Can someone please explain to me how this code works. It's baffling me. It's meant to go with the new input system.
Vector2 inputVector = playerInputActions.Player.Move.ReadValue<Vector2>();
Whereas before, I had to write all that
Vector2 playerDirection = new Vector2(0,0);
if(Input.GetKey(KeyCode.W)) {
playerDirection.y = +1;
}
if(Input.GetKey(KeyCode.S)) {
playerDirection.y = -1;
}
if(Input.GetKey(KeyCode.A)) {
playerDirection.x = -1;
}
if(Input.GetKey(KeyCode.D)) {
playerDirection.x = +1;
}
Like how does it know to just ReadValue and understand -1 or +1 for this Direction. Insane
You can essentially see your old code represented through the configuration UI by double clicking the input actions asset.
You define these values else where either on the map or UI ^
that input vector there I believe is just the callback if you wanted to use those values in code
There are tutorials and documentation pinned in #🖱️┃input-system explaining that as well.
Hey, I'm looking to implement this 2D Controller into my first mobile game and make it so the movement will be controlled by a joystick. I already have the joystick set up and have installed the unity package but I'm not sure how I can implement this. https://github.com/Matthew-J-Spencer/Ultimate-2D-Controller
A great starting point for your 2D controller. Making use of all the hidden tricks like coyote, buffered actions, speedy apex, anti grav apex, etc - Matthew-J-Spencer/Ultimate-2D-Controller
How would I go about debugging code that controls resolution and full screen mode and the likes?
Make a debug build
None of what I'm trying to test for applies to the normal editor play mode but obviously I can't read my debug logs in a regular standalone build
How does that work
Will try it, thanks!
I'm trying to addforce from one object's script to another object for a knockback effect but I'm missing something and could use another set of eyes.
private Rigidbody boxRb;
ah, ignore that
I'll just put it in a link
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Any of these debug.logs printing
When they aren't commented out they all work
I'm getting no actual force being applied
- You are looking for a counter component? Is that really the right one?
- Player input/movement might override the force
OnCollisionEnter here isn't the object that's not being pushed right cause you're destroying it instant;y
Also is your Player kinematic or dynamic?
He wants to push the Player if hes close to the sphere when it touches the ground
private void CheckForPlayer()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, 3f);
foreach (Collider c in colliders)
{
//Debug.Log($"Detected: {c.gameObject.name}");
if (c.GetComponent<Counter>())
{
//Debug.Log($"Detected: {c.gameObject.name}");
Vector3 direction = (transform.position - c.transform.position).normalized;
boxRb.GetComponent<Rigidbody>().AddForce(direction * blast, ForceMode.Impulse);
Debug.Log("Force was applied to boxRb");
//Debug.Log("Player takes damage.");
}
}
}
Few thing here, considering using TryGetComponent as that's less error prone and easier to debug against
I have to look for the counter component on the bottom of the box due to a deactivated collider on the overall box, and I get no force even if still.
Oh and btw destroy has a time argument, like Destroy(gameObject, 0.1f)
Yeah but your movement might apply velocity 0, 0, 0 which would override the velocity of the impulse
First thing to do is figure if it's a code issue and I'd make sure the component that being retrieved correctly, otherwise could just be not set correctly on the editor.
Oh yeah right you apply the force to the rigidbody of the sphere, not the player
dynamic
boxRb is your sphere, you need to get the component of the "c" object
I don't understad this error, can someone help?
the c object doesn't have a rigidbody, and can't. I need to apply the force to the parent object of c
There is getcomponentinparent or smth like that
Also you can put a Script on c, which references the rigidbody in a public property, which you can then get off that script
But if you're doing a cast using Overlapsphere, you should be getting the object with the collider, so if you're saying the parent of c is th eone with the rigidbody then it also must have a collider
It has a collider but it's deactivated because it's a container
I think the getcomponentinparent might work but I gotta run the kids to school before I can try. Thank you all
Is your IDE set up? Invalid parameters would be something it'll alert you to
But the issue reads that you're invoking a method but sending in the wrong parameters
!ide
!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
my ide is configured
this is the code
You can't use an int as input to a context menu method
There's no way you could provide that value via a context menu
is there a way to make a navmesh agent run out of a trigger?
more context
I want an enemy in my game to shoot a bullet and then run a certain distance away from the player before shooting another shot
That's just logic then. Assuming your enemy is patroling via path calculations, you want some sort of detection method like OverlapSphere to hault the current pathing. Then, calculate a new pathing towards the player.
If enemy is atleast 5 units close to the player -> shoot
else continue pathing
If enemy shot a bullet, find a position on the navmesh 5 units away from the player and path there
How do I find a position 5 units away from the player though? Is there a certain function for that or something?
ty
Sometimes you may not get a position, so the idea is to fallback on a count of sampling. If you can't find one then that's up to you to decide how they should behave.
Lot of ways about this, such as having nodes on your scene you consider as cover which you can just use those as the position
Hey, I'm a first-time coder and would like to learn how to add UI in my game?
I don't know how to insert my artwork as in what the resolution has to be for it to look good
Can someone help me to make a peice of UI where you can see the characters age,health,gender, and happiness things like that
Howdy there,
I'm looking to create a timer that will work with a collider area and track how long the player has been in that area. If they're in that area too long, it calls a function. When they leave the area, the timer stops.
Can anyone please help?
uI_Fade.FadeToPurple();
if(Time.deltaTime == timeUntilPoison) {
playerHealth.Death();
}
}
void OnTriggerExit2D(Collider2D other) {
uI_Fade.FadeToClear();
} ```
This is what I currently have but I feel like the if() is a little off.
What doesnt work?
is there any equivalent to a raycast that just makes a sphere with a specified radius around a transform, and checks if anything collides with that sphere?
Time.deltaTime == timeUntilPoison is almost certainly wrong. deltaTime does not accumulate. you also don't want to compare floats directly, and for time you wouldn't want to compare it exactly or approximately, you'd want to see if the time is greater than or equal to your desired time
@wraith phoenix Just a tip: instead of separate methods to fade for every color, make one FadeTo method with Color as a parameter . . .
Just check/compare its position with the world position . . .
OverlapSphere
thank you! I did it in a very stupid way by just making a sphere trigger, and adding anything that enters it to an array and anything that leaves is removed from the array, but this is so much easier and i'd bet much more performant too.
There is a distance method to see how close the GameObject is to a position . . .
Another idea is making a secondary gameobject and using a collider on that then using OnTrigger() methods if you want something more visible on the scene
What's an OnTrigger() method?
if the gameobjects have a collider then a physics query like an overlapcircle would
So far, all of it lol.
I can start debug testing
https://docs.unity3d.com/ScriptReference/Collider-isTrigger.html
Docs give some more methods
Mind you that rigidbody is only required to register the events, but can be set as kinematic
some physx bs
I;m looking into this. THat will be my next step once I get a fade to occur from the collider enter/exit
of course it needs a rigidbody
because colliders just aren't enough i guess
wait
wouldn't OnTriggerStay() have the exact same event?
is there a C# unity command that tracks time in a collider?
All triggers are similar with some additional conditions, so yes
add time.deltaTime for every frame that object is in the collider
now i feel extra stupid for making that makeshift solution as opposed to just checking for input on trigger stay
wdym by "invoke the colliders directly"? 🤔
box2D you can just check if something is intersecting via collider
instead of having to use these events
What about using an await function and then disabling that await if they exit the collider?
don't have experience using await so i can't comment on that
you can check if something specific is touching the collider with the IsTouching method, but the methods like Collider2D.Overlap still require a rigidbody
unless you're talking about couroutines
https://docs.unity3d.com/ScriptReference/Collider2D.Cast.html
This method specifically. I think I've mentioned it before around here
Maybe I need to make a coroutine for it to work
I am using the Player which has a rigidbody.
Note: Use of Collider2D.Cast() requires the use of Rigidbody2D.
no idea why that note isn't on the first overloads shown, but the method does require a rigidbody
Oh, I mean having to use the Trigger method specifically
Sorry yeah rigidbody is still required unfortunately
do you mean the trigger physics messages? because that still requires a rigidbody on at least one of the objects involved in the overlap
https://unity.huh.how/physics-messages/trigger-matrix-2d
It's just that I've a preference of doing stuff in Update primarily, so I'm not the biggest fan of just the general usage of OnTrigger() ect
so usually you fall back onto using the physic queries but it's something easily to work with on the editor visibly
Maybe I'll look into developing a small gizmos script per query for that specific gameobject
I did get some of the code to work.
if (other.CompareTag("Player")) {
Debug.Log("Player tag has worked with collider");
poisonTime = timeUntilPoisoned;
}
}
void OnTriggerStay2D(Collider2D other) {
if (other.CompareTag("Player")) {
Debug.Log("Player has entered Poison");
uI_Fade.FadeToPurple();
poisonTime -= Time.deltaTime;
if (poisonTime <= 0) {
Debug.Log("Poison time has reached zero and if statement fired");
playerHealth.Death();
}
}
}
void OnTriggerExit2D(Collider2D other) {
if (other.CompareTag("Player")) {
uI_Fade.FadeToClear();
}
}```
My uI_fade is not wokring but the poison area kills me after 3 seconds
depending on what your FadeToPurple method actually does, you might be restarting the process over and over
This could explain it
I likely need to move it to OnTriggerEnter
if (fadeRoutine != null){
StopCoroutine(fadeRoutine);
}
fadeRoutine = PoisonFadeRoutine(1);
StartCoroutine(fadeRoutine);
}
private IEnumerator PoisonFadeRoutine(float targetAlpha){
while (!Mathf.Approximately(poisonFadeScreen.color.a, targetAlpha)){
float alpha = Mathf.MoveTowards(poisonFadeScreen.color.a, targetAlpha, fadeSpeed * Time.deltaTime);
fadeScreen.color = new Color(poisonFadeScreen.color.r, poisonFadeScreen.color.g, poisonFadeScreen.color.b, alpha);
yield return null;
}
}
Here is my fade FadeToPurple method
not sure why it isn't firing
put some logs in there to see what is actually happening
I'm encountering the weirdest thing I have ever seen. I'm creating a new empty scene, add an empty GameObject and add the following script:
public class AuthManager : MonoBehavior
{
public static AuthManager Instance { get; private set; }
// some other fields
[SerializeField] private string baseUrl = "http://localhost:8000/api";
// etc. (but nothing special)
private void Awake()
{
Debug.Log($"AuthManager Awake called. {Instance == null}");
// Implement Singleton pattern
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(this.gameObject);
}
else
{
Debug.Log("Duplicate AuthManager detected. Destroying.");
Destroy(gameObject);
return;
}
DontDestroyOnLoad(this.gameObject);
}
}
The gameObject get's destroyed after seing AuthManager Awake called. True in the console. And there is no Duplicate AuthManager detected. Destroying in the console either. It makes zero sense to me.
yes, use a layermask
https://unity.huh.how/physics-queries/layer-masks
how have you confirmed that it is destroyed?
No, I haven't.
But it disappears and the start method is not called.
wdym it disappears?
in the scene tree.
did you look in the DDOL scene where DDOL objects go?
No I didn't. But the start is still not called. is that supposed to be right?
i see no Start method on that component. so how have you actually confirmed any of this
I've created a new Empty Script:
public class Test : MonoBehaviour
{
public static Test Instance { get; private set; }
// some other fields
[SerializeField] private string baseUrl = "http://localhost:8000/api";
// etc. (but nothing special)
private void Awake()
{
Debug.Log($"AuthManager Awake called. {Instance == null}");
// Implement Singleton pattern
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(this.gameObject);
}
else
{
Debug.Log("Duplicate AuthManager detected. Destroying.");
Destroy(gameObject);
return;
}
DontDestroyOnLoad(this.gameObject);
}
public void Start()
{
Debug.Log("Start called.");
}
}
Could I be doing something else wrong?
did you put this component on anything?
Welp, I works now. Uff. Thanks, I guess. It must be something else then
Sorry, it was something different 🤦
I didn't know about the DDOL
why
DontDestroyOnLoad(this.gameObject);
twice?
mistake. It's fixed now.
Elo again
Is there a way to check if the gameobject that i’m dragging in on top of another object
The way that i drag is to directly change the object position usinh OnDrag object.transform.position = mouseposition, not rigidbody speed
It’s 2D
Oh i found it. It’s from https://www.reddit.com/r/Unity2D/s/uRyme4h0vG
But i’d still appreciate it if there is a better way
Hallo, I have a quick question. I’m new to unity, how to change the background colour in unity 6(I can’t find it under main camera)
what background?
and how is this code related?
Camera.backgroundColor should definitely still exist in unity 6
Why would I not be able to drag a Canvas Text object into a public variable I created for it?
Show the the code for the public variable and show the component for the object you're trying to drag.
!ask 👇
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
public Text hpText;
hpText.text = "Box Health: " + boxHealth;
your text object is very likely a TextMeshProUGUI object, not a legacy Text object
yeah, sorry
use public TMP_Text hpText; instead
TMP_Text? since when that existed?
Since TextMeshPro existed
It's the base class for the two TextMeshPro classes
It's the shared parent class of both TextMeshPro and TextMeshProUGUI
and probably others
seems to be, learn something new every day
I'm using Text in another script and it works fine. Why would it be different here?
because you're using legacy text component with it..
Is that other script referencing an actual Text object instead of a TextMeshProUGUI object?
They're different components
They aren't interchangeable. You can't use a variable of one type to reference the other, in either direction
wait...I think I see
Show the inspector for the object that does work, and the one for the one that doesn't
what's the library declaration for the TMP?
use the quick actions in your IDE to add the correct using directive
Still ot able to add it and I'm getting this error on my 2nd line of script: Severity Code Description Project File Line Suppression State
Error (active) CS1061 'TMP_Text' does not contain a definition for 'TMP_Text' and no accessible extension method 'TMP_Text' accepting a first argument of type 'TMP_Text' could be found (are you missing a using directive or an assembly reference?) Assembly-CSharp C:\Users\joshu\OneDrive\Desktop\Unity Projects\Counting Prototype\Assets\Scripts\BoxController.cs 50
(not)
Well, check the documentation. Is there a variable named TMP_Text on the class TMP_Text?
https://docs.unity3d.com/Packages/com.unity.textmeshpro@1.2/api/TMPro.TMP_Text.html
why do you think the namespace for TMP_Text is TMP_Text ?
The other one was .text so I assumed it needed changed
No one, at any point, said to change the variable
don't assume, check
You need to change the type
my bad
ok, that got me over the hump. Thank you
is variable--; the right line of code to subtract 1 from variable?
Sorry for so many questions. I enjoy the coding aspect., but there's just so much to remember. Is there like a good reference sheet for beginners that anybody can recommend?
there are beginner courses pinned in this channel
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Well, to be a genuine nitpick; they all compile into variable = variable - 1.
If you decompile it actually lowers into variable--
I'm actually taking the junior programmer course through UnityLearn, but doing and remembering are two different things
microsoft docs and then unity docs for the unity API specifics
you remember by doing
if you write a player controller many times, then you will be able to write a player controller without even thinking about it
Hi! :3
there are hundreds of tutorials for that
ok
Guys can anyone tell me how do I add 2 pieces of string together?
there are beginner c# courses pinned in this channel, if you are not aware of the + operator, then perhaps start there
Do you mean string the data type
if not, you're going to have to actually say what you mean by "adding" and "piece of string"
I already solved the problem.
how do i change the material of an object thru a script? like if i want to change a ball to use a different texture by pressing a button
It seems like TMPro already convert numbers to string, so the error was there.
text mesh pro had nothing to do with converting the numbers to a string. its text property is a string and can only have a string assigned to it.
but what if i want to change the texture, not the color? or is that the same thing
you can change the entire material with that property
oh i see
the code example is merely just an example of getting the material. that is not the only thing you can do with it
You can get the material, and change whatever properties you want of it
For changing a variable in another script, you gotta declare the variable, define it in start, and do the math your wanting to do, but what sends the data back to the script you got the variable from in the first place?
That doesn't seem like what you do for changing a variable
you have to reference the script if which containts the variable you want to change then change that variable like so
public Script _Script;, _Script.Var1 = etc;
Then I’m doing it wrong lol
You need a reference to the thing you want to access, then you can do whatever you want with any public members of that object:
https://unity.huh.how/references
Choose the best way to reference other variables.
You don't get a reference to a variable
you get a reference to the object that has the variable
I wanna make a cue which can rotate as it moves around the ball, where can I start?
I tried the lookat method but it rotated it in axis' i didn't want
RotateAround method maybe?
You could also potentially give it a parent object whos origin is always at the ball when shooting, and use regular rotate methods
Depending on how your cue pivot is, you can also use LookRotation(direction, axis) : https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html
Parenting would also make it easier to make the shooting animation etc. because you could just move on local axes
That sounds overcomplicated
Is it?
nahh not at all . SetParent function works very well , just move the pivot item to the ball when you setup for a shot
makes many things including the rotation much simpler not more complicated
what would that do if it just makes the transform a child of the pivot point
I need to rotate it around the ball
well yes but the parent object now is your rotation item, this way it rotates around the ball.
think of the parent as a Pivot to rotate around
so i make the pivot a child of the ball?
no because if you move the ball everything will follow the ball, all you need is to set that parent position to the ball
ive set the pivot now but i dont know how to rotate around it
make the cue child of the pivot object, now just rotate the parent on the Z
you could but after you hit the ball you must unparent it
otherwise any child (including the cue) will follow the ball
oh ok
If i am moving the mouse to change the angle, how would the cue know what direction to face in
i have the pivots position and the cues position (where it follows the mouse)
the problem by parenting to the ball is that now you have to rotate the ball instead thats why its better to seperate the two
yeah i get that
but idk how the cue will understand what angle to point in
cause it will rotate with the mouses position
i assume i need to take the distance between the two and do smth but idk what it is
You want to target where the mouse is pointing ?
that depends on how you plan on rotating , its behaviour
i want to target a pivot
at the cue balls position
the pivot will be your rotation
usually transorm.up is your direction
you could rotate the Z with for example the delta of the mouseX
is there a better way to simulate fires spreading to a nearby component?
If I don't indicate a parent when defining a class, does it automatically have Object be the parent?
a parent when defining a class?
like a parent class
wouldnt I also need mouseZ?
So like [ClassName] : Monobehaviour.
iirc that means the class is a child of monobehaviour, so what happens if nothing's there? Is Object the parent?
Hi all, im getting this error and it doesn't quite make sense as i have followed the naming convention required?
Rpc method must end with 'Rpc' suffix!
[Rpc(SendTo.Server)] void CastSpellRpc(int spellNumber){ unitStats.Cast(spellNumber); }
yes, if your class does not inherit any class explicitly then it will implicitly inherit directly from System.Object
Mouse X
ah ok ty
why, that is only left to right
Maybe just call a method on that other component that would setup a coroutine of its own(if needed) and make sure the coroutine is not being recursive( the new coroutine should not start a new one before yielding). Or even don't make it coroutine based at all.
have you actually saved and recompiled the code?
how do you want to rotate the cue ?
It needs to know when its going above or below
so you want it at the exact position of the mouse?
how do i recompile it? isn't that what happens when you tab back into the unity editor? if so then yes
the cue? yes
like 8 ball pool
i want it
yes it should automatically recompile after saving and tab back into the editor. but if you've done something like turn off auto refresh for assets then it wouldn't, or there are assets that fuck with the compilation process (like hot reload)
okay so just do
var dir = cursorWorldPos - cuePivotTransform.position
cuePivotTransform.up = dir.normalized
how do i force it?
thanks 🙏 i dont get why transform.up is needed though
ctrl+r in unity should force an asset refresh which will trigger a recompile if there are any changes to compile
doesnt look like the issue
if you are certain that your code has been compiled and you are still receiving the error, then screenshot both the full error (including stack trace) and the inspector window when you've got the script selected so it shows the code that unity sees
so the pivot points where the mouse is, assuming you set it up as i shown in the GIF
void Update()
{
var mouseWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseWorld.z = 0;
var dir = mouseWorld - cuePivot.transform.position;
cuePivot.up = dir.normalized;
}```
that error is stale. clear it
doesn't clear and won't build because of the error. it goes away if i change it to not use RPC and comes back when i add it again
Are there variants of UnityAction that support non-zero arguments?
did you look at the docs?
ohhh, im on unity 3d
I was confused why up was relecant
relevant
you could also try the old school [ServerRpc] SomeMehtod_ServerRpc
then ask for help in the #archived-networking channel or in the netcode server, seems like possibly a bug
isn't that depricated and a bad idea?
I use it and works fine 🤷♂️
it's not a bad idea, but it isn't the preferred workflow anymore
just to try and see if it works
fwiw i'm not having any issue with using the RPC attribute 🤷♂️
Oh, I could just write something like this: UnityAction<T>
why not just use the System.Action , whats the benefit of UnityAction over that
well, doesnt matter anyway it seems
how did you write the method
[ServerRpc] void CastSpell_ServerRpc(int spellNumber){ unitStats.Cast(spellNumber); }
yeah idk ur seetup is bugged
ok ty ill ask in networking
First time toying with events, so not sure on the nuance between them. It looks like I can use either for my purpose though.
That being said, I don't really want manipulation of events in the inspector, so I might switch to Action
because you're doing 2D no?
I think you're confusing UnityEvent with UnityAction
UnityEvent is the one that is meant to be used in the inspector
UnityAction is like System.Action but with Unity handling the events ig
had to use 3d so I can get the balls to roll
without animating
so whatever UP equivalent is on your cue.
Oh I mean Unity 3D and 2D is the same thing, only thing that changes is the physics / camera view
forward right?
I did forward it kind of works
but it keeps angling on the z axis
i mean x axis
show your current Pivot / gizmo for the Cue
make sure its in Local mode not Global
yes you want transform.forward if thats Local mode
cast the mouse onto a plane here (if you're doing topdown)
if (Physics.Raycast(ray, out RaycastHit raycastHit)) {
_mousePos = transform.position = new Vector3(raycastHit.point.x, 0, raycastHit.point.z);
}```
I did that
so based on that example I sent, it would be
var dir = worldPoint - cuePivotTransform.position cuePivotTransform.forward = dir.normalized
just make sure the plane is in the correct axis
yh
The cue angles down, I think that's cause of the raycast thing I used?
when it comes closer
did you not click the link I sent
so you don't have to worry about depth accidentally hitting item with collider that will raise your ray
oh okay
Man, delegates are such a weird concept. Still trying to get a grasp on them
They are basically just a function stored in a variable
this guy has a really good video series on everything about it. https://www.youtube.com/watch?v=UL2XHN6uJCg&list=PLAE7FECFFFCBE1A54
old videos so the audio is a bit rough
been awhile since i watched it but i believe up to video 14 is all you need for unity stuff anyways
Yeah, I might look into that. I get the whole thing of them being a function in a variable, but their use case is kinda beyond my imagination. If I hadn't had to deal with them when modding a game, I doubt I would use them
Could someone help me fix a bug is beginner stuff I can screenshare
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
they're very common to use. anytime you want to notify about something happening, but dont care who is listening, you use delegates/events
Hmm. So are they more closely used in events among other things? That would make sense
I have this problem rn where the script editor would open but just show up blank
hmm show your External Tools page in Unity Preferences
also you should probably update to latest VS (2022)
can I screenshare you?
use screenshots
you can make a thread too, so we don't flood chat
What are you expecting to see in it? Are you opening a script or something?
You can reply in the thread.
- Run some function when you click a button, or multiple functions
- Detect if an actor gets damaged
- Detect if the scene changes
- Detect if a tween is complete
- Detect if the editor's play state changes
- Delay an editor action via
EditorApplication.delayCallto call a function on the next editor frame
etc etc, many use cases where you basically want to "emit" an event for any number of "listeners" to get that emission later.
Ah, it definitely sounds like delegates are closely related to events then, especially considering what bawsi said earlier about them basically being restricted delegates
If I'm thinking in that particular area/scope, it makes more sense
Yes. Also bawsi was talking about the literal event keyword which can be put onto a delegate variable so only the thing that holds it can actually run it.
Oh I see
@limber epoch enum is basically human-readable labels for integers
this is c# stuff. I suggest you check out the docs
thanks
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Is there a way to make one transform's rotation smoothly match another transform's rotation?
set it in LateUpdate?
learn about quaternion.slerp
Alright Ill do that
Also Lerp Smoothing might be something to look into. People usually do Lerp(current, target, Time.deltaTime) but that's not truly framerate independent
please do not recommend people to use Lerp incorrectly
wait, did I?
didn't I just tell not to?
Hello, i have an issue with my character controller script, for some reason its offset by like .15 from the ground, its the first time i use characterCDontrollers instead of rigidbody
yes, Lerp is start,end,t not current,end,c
hello I am making a 2d rpg and in it I have an npc who I want to follow a fixed path for 1 event another fixed path for another and so on pls guide me on that
That's why I told to look into Lerp Smoothing which is start, end, exp2(-lerpSpeed*deltaTime)
Lerp Smoothing is a great tool to make smooth following animations procedurally
oh
I just loaded my project and out of nowhere it looks like everything is gone
you didnt saved
you do not have a scene open
what do I do to fix it
you sure ? he have game objects
and the scene is saved
open a scene, usually in Scenes/SampleScene if you changed nothing
wait, isnt a scene supposed to be chached in Temp ?
yes, a dead giveaway
tho you cant have no scene without no scenes or am i wrong
you cant unload it
so idk
why are you looking in file explorer, look in the unity project view
Ignore
screenshot your project view
in the Editor not the Hub
Now go in the Scenes folder
you really need to !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
same for me
show console
yep, that is your next job, fix your compile errors
is it normal that even in fixedupdate, how my character controller jump is random
// Handle jumping input
if (Input.GetKeyDown(KeyCode.Space) && groundedPlayer)
{
// Set the vertical velocity for jumping
playerVelocity.y += Mathf.Sqrt(jumpHeight * -2.0f * gravityValue);
}
isnt the package broken ?
probably missing the Unity.UI package
or doesn't have the using
how u fix that i dont have mcuh time
look in the package manager
Do not check for Input in FixedUpdate
Only in Update and cache the value
Wrong
oh maybe because it was a rigid body too...
nope, never check for Input in Fixed because it does not run every frame
wtf are those tutorial i watched lmao
like most tutorials, rubbish
so what do i do to chache input ?
bool keyPress
...
Update
if (Input,GetKeyDown) keyPress = true
FixedUpdate
if (keyPress) {
// Your code here
keyPress = false;
}
oh
<@&502884371011731486> Spam
also funnyt part, its not even automated lmao
you would think they would be smart, but nope
MEE6 Is so powerfull it run on a phone
!ban 1295969937931636791 bot spam
valiant_quokka_11852 was banned.
even after this its still working 1fifth of the time
post your complete !code to a paste site
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
oh never mind, for some reason unity didnt refreshed the first time
how do i make a function for a event to trigger when you hold a key down
when i use void update it just keeps going and going when im holding that key down
i want it to only happen once when i press it down
you can use a coroutine
Is that not what you want?
Show your implementation
Ah wait ok i think i did it wrong i fixed it now
Sorry
how do i make a script to tell every single gameobject with a tag to do something
or just disable a component from them
you could use FindGameObjectsWithTag
Do it the other way around, make a script that has a static event and let all other gameobjects have a script that listens to that event
If there is no way around doing that by tags the answer above is your choice but thats generally not something you want to do
Don't want to do it often.
Once at the start during/after load is fine
The question is too vague to give the best way for this situation though. There are too many ways to do this and the best way depends on the specific use case.
private void Update()
{
// ... (Other code)
Vector2 direction = lookAtObject.transform.position - transform.position;
float lookDirection = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, lookDirection);
spriteRenderer.flipY = transform.position.x > lookAtObject.transform.position.x;
}```
is this a clean way to implement an object looking at another object? (2D space)
if it works it works
why not just use transform.LookAt and cut out the middle man?
doesn't work in 2D for some reason when I try to use LookAt()
or i might be using it wrong
by just putting in the object I want it to look at
rather than the look direction
this is top-down?
as you're using atan2
funnily enough, you can use quaternion's methods too (z-up)
yep
I used OverlapSphere to create a knockback effect, but it sends the player through the epicenter if they are running toward it instead of knocking them back. Recently ai was told player movement can override addforce and I was wondering if stopping the player movement prior to the addforce would fix that or if there was a simpler solution?
it depends on how you are moving the player. if you're using anything other than addforce to move them, then yes you will need to stop their movement ability for the duration of the knockback so you don't completely override it
Ok, thanks
Your code for the explosion may also be partially at fault
Can someone help me make a script that changes a scene?
I want it to be a button tho
We don't spoonfeed scripts here, I'm sure there are plenty of tutorials to achieve that, you may also want to check the documentation. I know for sure that in the beginner pathway on !learn, there is a final step that introduces you to scene management & scripted buttons to teleport from one scene to another
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
How to get the minimum width and height of a rect transform using properties of various child layout elements?
Hey, just wondering if anyone can help, im struggling with a jittery moving platform. im not sure if my code is the issue. Any help would be massively appreciated. ( the code works fine for side to side transformations but is jittery on up and down)
You are moving a physics object in Update directly via the Transform
that's your issue
You need to give your object a Rigidbody if it doesn't have one, turn on interpolation, and move it in FixedUpdate with Rigidbody.MovePosition
Thank you so much ill give that a try
When I do SceneManager.LoadScene("some scene name"). It will get rid of all the additively loaded scenes and just load a whole new scene?
Yes it will get rid of all other loaded scenes unless you load this one additively as well
how 2 add text 2 3d objects?
Add it in what way
You can either add 3D text objects to the world
or use a world space canvas
or embed text in a texture/material
Really depends on the effect you want
i want 2 make ui with code
This VS isn't configured correctly
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
https://hatebin.com/aqyeiknpdg
So this is my Loader class. I want to go to Loading Screen first. Then when on Loading Screen scene, after first update, it fires the callback saying the scene is loaded. Then I want to load the scene name I pass in additively so i do not destroy my Init scene which is loaded from the start of my game. For some reason when I press load. It loads Loading screen scene and playable scene again and again.
use a boolean or something to track when the scene is finished loading.. i think ur coroutine logic is the problem in ur code
This isn't even unity related
maybe contact github support
I deleted it just in case
Could it be that I load the scenes additively and the gameobject never gets destroyed hence causing the scenes to load infinitely
y i don't see the text?
have you tried resizing the boundary box, or using one character to "W" to see if it fits/appears?
yes
is Font Asset supposed to be unset?
yeah pretty sure it's not supposed to be
@onyx tusk try setting that field
how 2 add font?
does the same thing happen when you create a new text mesh pro GameObject?
what do you mean?
this is a GameObject with a text mesh pro component, right? just create a new one . . .
i used this
ok, now i again have a huge invisible square
how do i do this
do you get any fonts when you try to set the field
That's not the font TMP wants, you need to create an SDF file.
how do i make a reverse event
like instead of invoking the event the event gets invoked by something else
you'll probably want to check this out
https://docs.unity3d.com/Packages/com.unity.textmeshpro@4.0/manual/FontAssets.html
also, this is a non-code question in a code channel. Should be asking about this in #📲┃ui-ux
but also, you should have liberation sans by default?
The text won't be displayed if the TMP essentials aren't imported... no idea if the default font is imported with that or not
as he's got no font asset assigned, I'd assume it's imported with the essentials
needs to import TMP essentials first
you don't need to generate a font to use TMP. they have a default . . .
they don't, for some reason. but also, they're trying to use their own font, which you need to use tmp to generate
for some reason
Becuase, for the third time, they don't have the TMP essentials imported 😄
i thought their original issue was trying to add text to 3d objects?
how to make a variable avaible for the whole scene
i hope they imported it by now, lol . . .
There's no font assigned here by default.
They get no font asset in the drop down, because none are present.
The default font isn't present because they haven't imported the TMP essentials
they had a text element with no font asset set
Choose the best way to reference other variables.
i still dont understand
There are a lot of ways to pass information between objects, which strategy you want to go for really depends on what you're trying to do. Take a look at singletons. You can only have one instance of a Singleton, so you'll have a static method for accessing that instance. Let's say you want to track score in such a way that any object can read or modify the score, you could have a ScoreManager singleton with a score int, then if you want to add 100 points to the score from any script, you'd just do something like ScoreManager.Instance.addPoints(100);
Would turrent defender game considerd beginner friendly? how long would it take to code something like that simpel
Vector3 direction = (transform.position - c.transform.position * -1).normalized;
c.GetComponentInParent<Rigidbody>().AddForce(direction * blast, ForceMode.Impulse);
Anybody know why this would push the player away from 0,0,0
transform.position - c.transform.position * -1 is the same as transform.position + c.transform.position
What are you trying to do
If you want to reverse the direction, swap the positions: (c.transform.position - transform.position).normalized
When I load a scene additively while im still on the say loading screen. The additively loaded scene's awake methods will get called right?
Awake will get called on the objects in the newly loaded scene as they are loaded
So it may even look for objects in its awake while im still in the loading screen right?
It will do whatever you told it to do in Awake
if that includes "looking for objects", certainly.
Yeah like. I think my additively loaded scene looks for the camera object inside the loading scene.
Its possible yeah?
if you wrote it that way
is that what you told it to do?
Hey, that seems to have worked, reversing the positions. Thanks
One thing I'm a little unclear about is what the definition of "scene activation" is according to unity. mentioned here and never actually defined: https://docs.unity3d.com/ScriptReference/AsyncOperation-allowSceneActivation.html
I do believe if you delay scene activation, you might be delaying Awake/OnEnable.
but it's not clear
I mean no I do not want it to be clear. I just want it to call awake if the scene is loaded but i guess i am not doing it. Because in my newly loaded scene, when it gets set active, even though I have a camera, it says camera is destroyed. I believe it is because awake gets called in my new scene while im still on the loading scene because of additive loading. Finds the loading scene camera, when the loading scene gets unloaded it loses the reference and never tries to find again
sounds likely
You might need to evolve beyond whatever naive method you are currently using for finding the camera
Thats right. I need to evolve. Thanks for the help
Wohooo! I delayed the finding camera and it works.
I have this line off code, but it return null, if i restart the game, any idea why?
void Awake()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicManagerScript>();
}
Presumably there is no active object in the scene with that tag.
what do you mean by "restart the game"
you'd have to explain how you're doing that
and on which object this script lives, etc..
public void restartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
tis is my restart func
the logic manager is in the scene tree
when you saiy "it returns null" what do you mean
what actually issue or error are you seeing
The Error: Nullreferenceexception,object reference not set an instance an object PipeMiddleScript.OnTriggerEnter2D. sc 23)
is the error that pops off
btw is there a better way to writhe code in discord ?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
thx
using Unity.VisualScripting;
using UnityEngine;
public class PipeMiddleTriggerScript : MonoBehaviour
{
public LogicManagerScript logic;
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicManagerScript>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == 6)
{
logic.addScore(1);
}
}
}
and now the error appers, if the tirgger gets triggert. i seem like the logic is null, but why ?
if there is no exception being thrown in Start then whatever object is tagged with Logic does not have a LogicManagerScript component attached
this is the whole game, the logic (gamecontainer) was the script
and i really don't understand why unity didn't find the logic script
make sure that is the only object tagged as Logic in your scene
OHH MY GOD!! Somehow the EventSystem also got this tag. 2 Hours wasted
The sultions was so dumb easy, thank you!!
Now is good time to rethink the decision to use tags
you would be much better off if you pass the LogicManagerScript reference to the instantiated objects rather than relying on FindWithTag
https://unity.huh.how/references/simple-dependency-injection
I follow an youtube video.. ohh man, anyway i take a look at this. Thanks again !
Simple straightforward debugging techniques (Debug.Log) can always find such issues in less than 5 minutes
It's always better to actually debug your code than just guessing
Could anyone help me with something?
don't ask to ask, just ask . . .
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
!ask
I’m trying to generate a maze and this is the result.
I don’t want it to generate an incomplete one.
Any suggestions?
none of these screenshots tell us anything, so here's a wikipedia article:
https://en.wikipedia.org/wiki/Maze_generation_algorithm
yo is there a way that i can tag something twice? Because i am making a card game and need something for all cards and just per classes.
Tags are one per object, but there's no need to limit yourself to tags
make your own custom component and you can put whatever data on it you want.
Using tags is very limiting.
alr tanks!
anyone have any idea why input.getkeydown doesnt work on behaviour graph update state?
what doesn't work about it?
Should work fine.
not sure why but the key code valu differ from what i set on the graph
that doesn't have anything to do with GetKeyDown though
yeah just realize the problem
Thanks this helped. So a ray will just pass through anything in it's way, and a plane can be used to detect if it's inline with the ray?
any way to make a plane to a limited size?
When making a turn by turn game, what is the general design to schedule turns and moves etc
a ray hits anything with a collider and will stop at the hit point. Raycasting onto a plane is like putting a point on a flat piece of paper
okay nice, and how can I limit it's size?
the onmousedrag function only recognizes when the mouse drags on colliders which are on the parent or children of the parent right?
cause I did onmousedrag when the parent has no collider, only a child has one
yeah iirc script and collider should be on same object, I don't really use onmousedrag, i usually use raycast or the event systems Ipointer interface
but the script and collider isnt on the same object, unless colliders on the children count
i don't use it so not sure.
what are you trying to do ?
it worked, was just trying to make the pool cue move only when holding mouse down on it
How can I limit a planes' size though?
On the docs I can't see anything ab it
its a flat plane through the level, don't think you can
you would have to replace it with maybe a box collider and do a collider.Raycast
Is having two colliders on one gameobject, each with a different purpose, a bad idea
oh I can use a collider as a plane?
na but you can raycast on a collider
okay nice
probably not what you want though, you should be fine with plane. How come you need specific size
I am playing pool on a table
but the current mechanic isn't working how it will in the end
wdym by that?
rn it can move anywhere, in reality it will have to move and rotate around the ball in orbit (like 8 ball pool)
thought you fixed that?
its not broken, it's just not as intended
How could I restrict it's movement in an orbit
a circle
yeah that worked
Hey guys, what's up...?
Just to make sure, which one is better for the new Input System
Invoke C# Events or Send Messages...?
I mean right now I'm using Invoke C# Events and it works, but if I had to call my methods (when I make a state machine later), I don't think it's letting me do that
Well...I don't know how to call methods with Input CallbackContext as the parameter
I just use the actions directly, so I don't use either.
With the InputAction reference thingy...?
You can assign actions to a variable in the inspector with InputActionReference. Then you can use the events yourself like .action.performed += MyEvent;. Otherwise if you are starting out, try out all the options to find a way that you think works best for yourself 😄
Yeah that's true, I'll test it out, thank you
Send Message uses strings - always try and avoid using strings for calling things, slow.
At the moment I'm using Invoke method and I think it works good
But if I had to call those methods inside a state machine I might build later, how would I do that...?
Because the parameter is a weird Callback Context thing, I'm not sure how I can "call" that
InvokeMethod uses a string to... don't use it
Already told you ... !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
If your IDE has not underlined errors in red you also need to configure it
You've most likely named your own class SceneManager
A state machine
problem is,
its made by oculus themselves
what version of unity are you using?
It's not present in the docs until 2022.2
do i delete it?
no..
you use a version 2022.2 or newer...
which, 2022.3.5 is
trigger a recompile
i switched to 2022.3.51f1 and some stuff stopped working
yeah, that's possible.. gotta fix it
you have 2 choices
1- update and fix all the stuff that breaks
2- you can't use this from oculus
or..
3- fix the oculus code to work with 2021.3.33 -> biggest task
And have you named one of your own classes SceneManager
Thanks, and that is the simplest method?
Just gonna have player 1 turn, player 2 turn and the phase when the ball is hit and is moving (in pool)
how do i make a script using events that get invoked instead of invoking and works for multiple gameobjects
this question is super vague and senseless
okok
Just be a bit more specific with what you’re wanting to do
sorry
Color
oh
Anyone know how to make text disappear behind this image as it scrolls? Does it need to be in another layer behind this one?
yeah, like it disappears either once it scrolls into the image's border or before it
It needs to scroll upwards but also toward the image?
you can just change its visibility once it crosses the border
There's probably a doTween to make an animation for that
You'll need to make each line be a separate object
And each object has a trigger event or you can just coordinate the animation with DoTween to do what you want to do
Hope it helps
does anyone know why this doesnt wait for a time between 1 and 5 seconds?
IEnumerator DelayedExplode(Transform gun)
{
yield return new WaitForSeconds(Random.Range(1, 5)); // Wait for a random duration between 1 and 5 seconds
// Detach and explode the gun after the delay
GunDetachAndExplode(gun);
}
It should be. What makes you think it doesn't?
Try adding logs before and after the wait and see the time difference in the console
btw this would only return 1 to 4 seconds (you would need to add f suffix to get max inclusive float version)
trying to learn csharp, thinking about watching an older tutorial from freecodecamp, 6 years old, does that matter or should i look for something newer
It doesn't really matter. The language didn't change over that time(new features were added, but that's beside the point).