#💻┃code-beginner
1 messages · Page 213 of 1
I feel like there must be a reason for that i'm missing
The reason is that that they are not really meant for being assigned dynamically at runtime.
And overall, unity tags are somewhat useless.
You'd usually have your own mechanism of object identification.
Just make a script with a string property or even a list of strings, use those to identify objects
That's fair. My usecase is in a modding scenario so i totally get that nothing is inherently designed to support that but man it's not a fun hard limitation to run into aha
Looks like the related functions and properties are handled on the c++ side of things so i'm guessing maybe hardcoding it helps for performance while using findobjectbytag and such
target is a property in Editor class which your custom editor inherit from
It's just the object the editor was made for
It looks like Unity doesn't like line 10, I know the RunProceduralGeneration works so that's not the problem. This is the warning in Unity You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
I have a particle system that sends waves progressively faster to warn that an enemy is about to explode, when adding sounds, there is a way of making it in sync with the particles or do I have to do it manually?
why does SimpleRandomWalkDungeonGenerator inherit from MonoBehaviour?
actually, it seems that the warning is just a warning but there is an error on line 21 in this class - the weird thing is that the button on the Editor is running this same function but is not complaining about this line at all
It shouldn't be, it is inheriting from AbstractDungeonGenerator
which means AbstractDungeonGenerator inherits from MonoBehaviour
why
no idea, I'm just trying to understand how this is working, got it from a youtube video
if you do not need any of the messages like Awake, Start, Update, etc and you do not need to attach it to any object as a component and would rather construct it using the new operator, then do not inherit from MonoBehaviour
I know that this button in the editor is working with this code, but not sure how.
but if I remove that then I get this error
in the editor's script
if you need this to be a MonoBehaviour, such as for attaching it to a gameobject like you are in the screenshot above, then do not instantiate it using the new operator
You could manually emit bursts from the particle system and play sound at the same time
either get a reference to the existing one, or create a new one by instantiating a prefab or using AddComponent like the warning tells you
omg! that works great, I just exposed it using [SerializeField] and then reference it!
is there a way to hide a game object without disabling its scripts?
2D or 3D?
2d
Layers
Disable only the renderer
let me ask a different question: is there a way to enable or disable a script through script? if that makes sense
i think that will be better for me
Yeah, the enabled property
Only scripts with unity methods can be enabled though (or at least react to it)
ok thanks'
Only Update and stuff like that will be disabled
All other code will continue to run if called
Oh, that was correct doot. .enabled = false
Oh, mb
gameObject.GetComponent<EmailSender >().enabled = false;
Hey, I'm trying to make a snap grid controlled by mouse for a battlefield TCG I'm designing. I can't get the grid to actually snap the object though.
When I move my object on the board, it doesn't snap
Also yes, I used GPT and modded what was needed, but I hit a stone wall.
I need help finding a Beginners course on AI on Unity Learn. Preferably 2D
Where are you moving it?
Also !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.
Oh, yeah.
What did you find so far?
What is the transform parameter in the TileChangeData constructor?
The documentation is too vague
I haven't found much on it. I look through the browse section and see things like NavMesh and Functions, but don't see any Unity AI tutorials
I have these spawn points but I can't seem to drag them into my List<Vector2Int> serializedfield, am I supposed to be using List<GameObject> instead?
transform is not a vector2int
use List<Transform>
It's a transformation matrix determining position, rotation and scale of the tile.
But there is already a Vector3Int position parameter...?
Well, ai is a very abstract term. Maybe start by looking at finite state machines or behaviour trees.
What should I set those to? The tilemap's transform?
That determines the logical position in the grid, but transformation matrix is applied on top of it I think.
lookup LlamaAcademy he covers all things navmesh
Thank you! However, I'm not looking for navmesh right now. I am looking for tutorials on simple AI behaviors.
If you don't want any changes to position, rotation or scale, use Matrix4x4.identity.
yeah they cover a whole series of AI..
thank you
Okay, I'll check it out.
Simple ai would be what dlich said. Fsm and behaviour trees. Then getting more complex you have things like Utility, GOAP and others
Usually best to look for a specific one rather than just "ai"
What you're probably looking for is a behaviour for computer controlled characters, which in itself is already a very ambiguous thing. For example, ai in a 2d platformer would be very different than a simulator, like Sims or something.
Wrong ping
somehow I am getting index was out of range error, am I missing something here?
do your list have elements?
The only case where that would happen is if enemies is empty.
I have 2 chickens (same prefabs)
Debug it in your code.
We don't know if that screenshot corresponds to what happens in reality.
also make sure you dont have a copy of this script somewhere with missing elements..
How do you get references, tips, whatever you call it in visual studio?
!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
• Other/None
thank you, that was it!
I’m assuming that’s a commonly asked question if there’s a command for it
indeed 🙂
how come my play button isnt clickable until i disable my floating joystick?
probably covering it
is it blocking the play button??
not really
that's not definitive enough. check if it is or is not . . .
Inspect the Event System gameobject during playmode and find out
so line 28 should generate a newEnemy gameobject as a child of whichever gameobject is holding this script right?
No
Nope . . .
it instantiates it as a child of spawnPoints[randPosition]
you can hover over the method implementation for a hint at the parameters
Wait, is spawnPoints[randPosition] a transform?
and if you do the secret visual studio hotkey handshake you can pullup a list of overloads inside of visual studios itself!
i checked the event system. nothing changed
Then you need to use the transform of this GameObject (the script is on) . . .
but when i disable the joystick, my play button slightly changed colour
show me
while hovering the button you cannot click in playmode, screenshot the event system in inspector
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I made some mods to it, but it still isn't wanting to snap
hold on ill get back to you
Weird, it seems debug on line 21 is running just fine with results, but line 22 is not running because the Debug.Log() in 27 is not firing. What am I not seeing here?
because thats not how you call coroutines
even the IDE is suggesting the fix..
the 3 dots, pay attention to them
gotcha, didn't know this!
ty!
why did you add that random .transform to spawnPoints[randPosition]? if spawnPoints is an array of Transform then that is 100% unnecessary. it also doesn't magically make it do what you had previously asked about, if you want to use that transform's position and rotation but make it a child of this object, then you need to use the 4 parameter overload of Instantiate
I figured I didn't need this and was actually fine with the enemies being the child of each spawn points. I thought I needed the .transform on a Transform but now that I say it outloud it sounds a bit redundant
wait a minute, if I'm reading this correctly, FixedUpdate() is running every seconds so I'm generating a new Coroutine per second that repeats per interval right? so it'll grow exponentially?
What repeat?
I dont know what interval you are talking about, but your coroutine does nothing. It does all the logic then waits to do nothing after
You are just starting a coroutine every fixed update, that is all
But you are creating around 50 new coroutines per second
yeah by default FixedUpdate runs 50 times per second, not once per second
@rich adder im trying to send my video but the file is too big
a screenshot wouldve been fine
no shit, look how big the rect transfrom for the floating joystick is
yeah but im not sure if thats the issue
i made it bigger and the other buttons worked fine
I believe what i know
fix the sizing of the rect
but i want the floating joystick to be used anywhere on the screen
clearly have a pretty big misunderstand how the UI works in unity
check pins in #📲┃ui-ux
as this is not code related
well step 1 dont cover other UI elements you wish to click on with another UI element's rect transform
Alright I'm stumped.
Still working on this for 2 days and I think I'm overcomplicathing this.
All I want is for the mouse to move a 3D object (not on screen) to between these points, im not sure what the best way to do that would be.
My first instinct would have been to just do a raycast for these positions and tie some coliders to em. But then I run into the issue where the player has to find the EXACT spot the collider is at, and the collider isn't really 1 to 1 with the visuals.
My OTHER idea was to have the player "drag" that 3d object around and have the 3d object snap to the nearest valid position. Which I think would work better, but I'm not sure how to go about implementing that. I've throught about turning all these points into screen space and handling that way, which I already have the logic to do, for the most part. But I'm not sure how to do the logic for the snapping or dragging of the 3d object TO those points. Someone have any suggestions or a resource or something?
simplify the whole thing and use Physics overlap
with your second idea
Physics overlap?
actually why not store those inside an array of positions and maybe check the 3D object which one is closest distance and just snap to it
in what sense?
Like, how do I turn the mouseInput into a 3D vector that returns the closest point?
Or correction
MouseInput into the snapPoint
You want that done after the placement right?
make object follow cursor with a ViewToRay
I need the mouse to move that cube to those point based on where the mouse is on screen
ooooh
then snap the object on the board, on mouse release or whatever snap to one of the pos
view or camera?
put a simple flat collider on the top of the board for easy "surface snapping"
So 2D collider above the board. Find the nearest point from the hit location. Snap the Cube to that point?
it is
OH I was just going to make it 2D cause this would be a fixed camera angle
Not to mention I wouldn't want the player to be able to hit the collider from the side
I guess technically speaking it would still work the same
Well I meant the side faces not the bottom face
but either way It doesn't make a difference, if anything, you're right a cube would probably work better if I didnt' want the fixed camera angle
Cause at the end of the day, the cube would still just snap to the closest point
right
There seems to be a lot of ways to spawn enemies based on a timer. Obviously there are pros and cons for each method, is there a concensus to which is decent to use for a first project? I'm leaning toward InvokeRepeating in Start()
Coroutines
IEnumerator Spawner(){
var waitTime = new WaitForSeconds(timeBetweenSpawns);
while(true){
//Spawn
yield return waitTime;
}
}```
Anyone know if there is a way to display a variable in the inspector if the variable exists only in a state script? The state script doesn’t attach to anything, only the state manager does, so it’s not letting me use public/serialize field to display the variable I want.
There is no consensus. I'd recommend a timer in update.
First, second, or third doesn't matter. Use what you can understand and achieve: a variable as a timer in Update, a coroutine, a custom Timer class, InvokeRepeating, async, etc . . .
Make sure to serialize the state script so it csn appear in the inspector . . .
You can serialize the state script itself? 😮
I had no idea (messing around with state machines for the first time ever)
You have to serialize C# classes/structs to appear from the inspector. It's nothing to do with a state itself . . .
are you talking about the Animator State scripts?
I see, thank you. Normal default classes I’ve used all allowed that automatically so I didn’t know!
No I’m making baby’s first finite state machine. For character movement and behaviors etc
ahh ok
I am not sure what you mean by default classes, but any class derived from MonoBehaviour can attach to a GameObject, meaning it is serialized and will display its fields . . .
what's the recommended way to store global variables like a kill counter across the whole game? I'm thinking of adding it to the menu gameobject and pass it as a reference to the bullet script so that it can increment upon collision - is that a bad idea?
bullet script should not be dealing with UI
Use events. A projectile should have no knowledge of the menu . . .
it's not, it increments the kill counter, there is a UI that reads that variable - or is that the same thing as dealing w/ UI?
You mentioned a menu GameObject, so we figured it was connected with a UI . . .
ah I see
Maybe I’m misunderstanding then. My state script doesn’t use monobehavior, and it doesn’t attach to a game object. The state manager script attaches to the game object and that script uses the state script.
then the state script has to be marked as Serializable
gotcha, but the event will have to increment a variable right? where does that variable usually live (as best practice)?
keep track of it in a stats manager or something
Yeah, apparently, I didn’t know that, thank you both!
good idea, I'll keep it on the player as it's a "stat"
The bullet shouldn't deal with a kill count either. When an enemy is defeated, send an event that a GameObject listens to. That GameObject can increase the counter or in another script (GameObject) to increase a counter . . .
I usually do that, keep my all my stats in one script then it can be easily saved. All it does is send an even t like OnStatsChanged or something, that scripts listen to display it, like UI etc
Yes, the state script is a regular C# class; therefore, you have to serialize it (using the attribute)
Search: how to serialize a class Unity . . .
https://docs.unity3d.com/ScriptReference/Component.BroadcastMessage.html is this overkill since it sends to every MonoBehaviour in this game object or any of its children.
its ugly dont use that
learn actual c# events
Avoid SendMessage and BroadcastMessage at all costs . . .
private void RegisterNetworkObjects(NetworkRunner runner) => runner.RegisterSceneObjects(networkObjectArray);
error CS7036: There is no argument given that corresponds to the required formal parameter 'objects' of 'NetworkRunner.RegisterSceneObjects(SceneRef, NetworkObject[], NetworkSceneLoadId)'
How to Solve It!!
Make sure you pass the correct arguments based on the method parameter(s) . . .
finished my junior programming course 🥳
now i guess it's onto the creative core stuff
honestly i feel like the junior programmer stuff is missing a lot, there wasn't anything about raycasts which are pretty essential
Watch this video in context on Unity's learning pages here -
http://unity3d.com/learn/tutorials/modules/beginner/physics/raycasting
How to use Rays to detect line of sight and angular calculations.
Help us caption & translate this video!
bro-
bro i'm not asking for a raycast tutorial
i'm just saying it wasn't included in the junior programmer course, which covers a lot of bases otherwise
fr hittin me with the nerd emoji rn
Kind of hard to tell with what you lead on . . .
Junior programming helps learn the basics of C# using the Unity engine. Raycasts are just a part of the physics engine to check for colliders. That's a specific task unrelated to the basics and core concepts; it's not a requirement . . .
On top of what Random said, Nav was just nicely trying to help 🤷♂️
is there an issue with the way im intializing my array? it seems to be causing issues
So what is the problem
the slots are sometimes turning to null
Your inventory is public so everyone can modify it
i know, thats not the issue, im specifically asking about the way I initialize it
okay thanks
Not sure what that event(?) with raise and null parameter is about though.
I mean, the fact that you're invoking it with null as parameter is a bit sus.
I don't need to be
read pls
Parameter not the conditional checking
The ? and the null parameter are 2 separate things, so I'm not sure I understand what you're trying to say.
What's even a null event? The end of the world or something?😅
void events*
Aah, I see. Weird, but ok.
it works great
Fuck is a void event
i was questioning if i was just dumb and didnt learn something about events 😅
an event that doesnt send any data
i have int events and other custom data types that can be sent through events
easy way to connect logic and UI
for example when I swap an item in the UI, it just sends an event with the two indexes in the inventory and the logic swaps the items then updates the UI
An event in the void obviously🤷♂️
void specifically is a type, but you cant have void as a type for your event
Sounds like something from Stalker
Or Metro
Wait metro does not have anomalies
I was thinking Warhammer
its just an empty class
to send no data
Delit this
for the way I do it, you have to specifiy a type
Void class is creating some cognitive dissonance 😅
nah the way I do it works well
honestly that was the LAST thing i was expecting
its just for the events
This is cursed
My brain feels like it is getting a void event right now
i have to specifiy a type on the listener
therefore, if I dont want to send data, i use a "void" event
this looks awful
But seriously, it kinda wraps unity event without providing any benefit. What's the point?
Please look into how to implement a proper generic event bus such as here https://github.com/PeturDarri/GenericEventBus
read, thanks
i just adapted that
But, it's not an SO🤔
what you've shown is completely different to what you have
Adapted to the point it is unrecognizeable
Or are the events themselves SO?
I see
I can just plug these in to anything to and hook a function up using unity events
That is probably one of the worst posts unity have ever done.
its a good system
It is objectively not
Like let me tell you. I run a studio. If I get to see a system like that in your portfolio when you apply for a job I am immediately tossing your application in the garbage
And usually I am a very good and tolerant person. That is how bad this system is.
it works perfectly, is modular, and is very simple to follow
i dont see the issue
i dont think you understand the full system
a lot of things "work perfectly" aka do what they are intended to do. I could say the same about using the Find functions, or stuff like SendMessage
you having to declare that Void class should already be a red alert, that this infact is not working perfectly. All of us were even shocked to have seen it.
Imagine how someone who has to work with you would react
i disagree man, the void class could have easily have been called NoData or something similar
so? the name is irrelevant. you are declaring a class with nothing in it. this is what i would call jumping through hoops to make a system work
you could name it OogaBooga for all i cared
it is not jumping through hoops though
it just an event passing no data
somewhat of an edge case you could say
you know what else passes no data? Action
I think the listeners won’t expect their publisher passing a null to them….
Imagine you receive a package and open it, nothing
is everything that you need to develop in unity learnable in unity learn/docs
i can see cases where it makes sense that the data could be null, but yea intentionally passing null is just weird.
It's more than enough to get you started.
depends what you are talking about. you will learn how to use unity's API and there are pathways that help you make the most basic of games. But you arent gonna learn to make a fully complete publishable game that gets money on steam
using c# events you need to have references still, this allows ui and logic to function seperately with no knowledge of each other
you dont
you can have Action which takes no parameters
and then Action<T> which can take one parameter
and I think there's ``Action<T,...>` up to like 16 arguments.
they are referring to something else, the implementation for events they are using is a bit above #💻┃code-beginner message
i just asked a question about an array and got chewed out for the way i do events
lmao
that doesnt change anything. you can still write your code in a way so that it operates with no knowledge of each other
yes but using just using base c# events does not allow for that
i understand an event bus is different but I don't want to implement that as I don't fully understand it
my system works just as well and accomplishes the same thing
I like the sound of UnityEvents living on ScriptableObjects. Give them a subscribe/unsubscribe and publish method.
Pretty good way of having a designer friendly event system.
that's exactly what I do
I think you have Monobehaviours marked as listeners though
yes, i guess you could say that's a limitation
Only one event, right?
no the downside is that you need to have a listener on the gameobject to respond to events
so my system only works with monobehaviours and other SOs
base c# classes can't recieve events
but so far I have had no cases where I need that so
for example,
You could implement an overload of Rise that doesn't take a type.
You see the real big dick play would be doing...
public class Void
{
public static Void Instance {get;} = new();
}
and then passing
Void.Instance
these guys in here would love it
🤷♂️ its not like it affects us or anyone that commented truly cares. we are just pointing out what we consider to be flaws. Basically as Uri said, if you show this system on a portfolio, you will get a few raised eyebrows
i just find it funny that I just asked a question about an array and you guys chewed me out when I frankly didnt ask for that advice. I don't think Uri saw how my system worked off the one picture they saw
I think it's just that passing null as a parameter is usually seen as... odd. Functions usually expect to be given things to work with.
yes I could easily make a overload with no parameters
just never did it since it works fine
Haven't we all had a phase where we had to write overly complex code that seemed good at the time?
where do i ask for help about unity inspector things?
Depends, general questions in #💻┃unity-talk and if you made a custom inspector probably #↕️┃editor-extensions
can someone look at my code and give me guidance on making it easier to read and manage. its my character controller script and it contains 3 main section: detect objects, go to target, look at target. i feel like it shouldn't be more than a few hundred lines of code. but instead its over 2,000 lines of code.
iv been working on it for a few months on and off and its getting bigger each time, and im not sure how to restructure it. im thinking of trying to splits each section into their own script. and then maybe split those into smaller scripts. but im not sure how im going to go about that as i am a beginner level 'coder'.
I've heard about 'dependency injection' a couple times recently, is that essentially the act of setting the value of a field through the inspector?
No, DI is the ability to inject references to classes into other classes by registering them to a general provider. This makes it possible to configure services that are manually registered based on the required type, or just for convenience so you don't have to manually write out dependencies
It's more useful in non-Unity .NET applications, really. Especially because Unity doesn't have proper support out of the box
Is that why there tends to be third party tools for that?
Hey Peeps,
kinda riping my hairout writing a script to control animations i have this block of code
{
animator.SetTrigger("pop");
}```
its in the update function, but the animation dosnt change
however manually setting the trigger in the editor changes the animation is my code wrong?
objecty is set to postion Y in the above line
I suppose it's also mostly because it's very opinionated how dependencies should work
In Unity you have various different ways of creating and disposing dependencies
If you register one, should it exist until scene change maybe, or should it be disposed when something else happends?
I think stuff like this is left to libraries due to how much can be configured
Either way, you can just write your own, because it's not a complex system to do (unless you're a beginner ofc)
I see
But it's probably also because DI usually works with constructors and Unity doesn't use those
as i'm still a rookie, is it something worth putting some time into studying or could it mostly just be another approach I could bear in mind?
Dependency Injection as a whole is important to understand, even if you never use it in Unity
It's a general term used by a lot of languages and frameworks
In that case I'll give it a further look later on
i am making a grapple hook and im using line renderer as my rope. I want to make it so that the line renderer doesnt just pop up and dissaperas, i want it to look like i shoot the rope from the guntip to the grapple point.
the code is in the link, thank you.
https://hatebin.com/ewzctdqrwm
anyone any idea why
{
ChangeAnimation();
}
void ChangeAnimation()
{
// Get the object's current Y position
float objectY = transform.position.y;
// Check the object's Y position and play the corresponding animation
if (objectY > 0f)
{
animator.SetTrigger("pop");
}
}``` dosnt work?
first thing is to check if the code is even being executed and if the if statement resolves to true
@languid spire massive derp moment 2 hours trying to figure it out, didnt actally attach the script works flawlessly fml ty!
occam's razor
PlayerInput+WalkActions.Get () (at Assets/Scripts/InputSystem/PlayerInput.cs:194)
PlayerInput+WalkActions.Enable () (at Assets/Scripts/InputSystem/PlayerInput.cs:195)
InputManager.OnEnable () (at Assets/Scripts/InputManager.cs:33)```
anyone know how to fix this error?
```public InputActionMap Get() { return m_Wrapper.m_Walk; }
public void Enable() { Get().Enable(); }```
line 194+195 ^
```WalkMovement.Enable();```
line 33 ^
You can animate it in a coroutine. Seems like you are doing something like that already?
m_Wrapper is null, whatever that is
If it's a component, be sure to add it
Otherwise please share all the !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.
@upper night Or what is this line doing? cs grapplePoint = Vector3.Lerp(grapplePoint, swingPoint, t);
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class InputManager : MonoBehaviour
{
private PlayerInput playerInput;
public PlayerInput.WalkActions WalkMovement;
private PlayerMotor motor;
private PlayerLook look;
// Start is called before the first frame update
void Start()
{
playerInput = new PlayerInput();
WalkMovement = playerInput.Walk;
motor = GetComponent<PlayerMotor>();
look = GetComponent<PlayerLook>();
}
// Update is called once per frame
void FixedUpdate()
{
motor.ProcessMove(WalkMovement.Movement.ReadValue<Vector2>());
}
private void LateUpdate()
{
look.ProcessLook(WalkMovement.PlayerLook.ReadValue<Vector2>());
}
private void OnEnable()
{
WalkMovement.Enable();
}
private void OnDisable()
{
WalkMovement.Disable();
}
}
@verbal dome idk thats no my code
Please share the code of PlayerInput.cs:194
Stop copying code that you don't understand
Oh sorry
I pinged the wrong guy lol my bad
Also, it might be possible it is null but that's because you should get components in an Awake method rather than Start
Perhaps it's fetched too late
its the pre-generated code from unity itself but here
@mossy sphinx Meant to ping you
Yo I got a question, I am trying to make a gameover screen with the buttons "Restart" and "Menu" and a start screen with the buttons "PLAY" and "QUIT" I can't seem to find a good way to make the player get sent back to menu from the gameover screen
Could someone help me?
no that wasnt the problem
@mossy sphinx Your lerp seems incorrect. You are doing this current = lerp(current, end, t)
When you should do something like current = lerp(start, end, t);
(Pseudo code)
Anyone got a clue?
You'll have to give lot more details than that
I am doing a car game and when you collide with objects you get sent to gameover screen and now when I press back to the menu and then play again I can not move my car
The script I use for going between different menu is just loading different scenes
but after loading "game" scene again it doesn't let me move my car
For performance reason, I should try not return array of function as possible? Maybe I remember wrong?
But what if I just want to have a function to return array of bytes?
I do put timescale to 0 after collide and gameover gets active
If you don't want to allocate a new array, you can pass in an array as parameter and have the method write to it
And maybe return an integer too that stores the count of valid items
Should I set timescale back to 1 somewhere?
I have a component that follows another objects rotation and moves accordingly
when I play it jitters
but when deactivate the component while playing and activate it again it doesn't jitters anymore
I used late update
but that just makes the jitter constant
So C# does copy the array if there's an array return from the function. The better solution is allocating outside and use ref to pass it to function as paremeter?Is my thought right? I'm being looking C++. Kinda mess-up...
You kinda got it, but arrays are always passed by reference in C#
Passing it into a function doesn't copy it
So another problem: My score keeps counting after gameover, what should I add to stop it?
Ohhh.Yes! That's true!
So should i write the start is from the guntip?
think about what you are doing
Yeah
thanks, i will try that later
Please configure your !ide before you ask questions here
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
• Other/None
Is there any way set component to active when play mode starts?
enabled property
inside of that component script
opening a box with the knife which is inside the box?
so use a sperate script for it?
yes
hello, one question. Im new in this
I created a canvas for a menu and added a image on it. Now im trying to add a button on one of the options so when clicked it moves to the next scene. However the OnClick() dont show the functions of the script so im not sure how to di it
they are public so thats not the problem
Did you reference an instance in the scene or the asset?
Your script must not accept any parameters
how can i paste code here?
!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.
You can paste !code using a site or directly
📃 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.
// Your code here
using UnityEngine;
using UnityEngine.SceneManagement;
public class CambioDeEscena : MonoBehaviour
{
string nombreDeEscena;
// Método público que cambiará la escena
public void CambiarEscena(string nombreDeEscena)
{
SceneManager.LoadScene(nombreDeEscena);
}
public void Prueba()
{
SceneManager.LoadScene(nombreDeEscena);
}
}
i did 2 to try
none of them appear
this right?
this isn't the class you've just shown
the file name and the class name need to be the same, so either you've got the file name wrong, or selected the wrong thing
and you should be dragging it in from a gameobject, not the project window
no you've put a script in, needs a gameobject to which the script is attached
so i dont have to drag the script?
depends on their unity version
You should be dragging in the game object
the button?
The game object with the component script you're wanting to access
I think it's pretty damn safe to say this is still a thing, 2023.3 isn't common enough for us to stop saying this.
which game object has the areria sript attached, that's the gameobject to use
it's also in 2022 in some versions
oh so i need to attach the code to the button and then drag the button to OnClick()?
To be fair, even if class and file name could differ it's very confusing and bad practice in general
So just make sure it's the same to avoid confusion
sure, that wasn't my point ;p
when i clear the resolved libraries in unity the aab building is perfectly fine but after resolving libraries the .aab not building perfectly
your point is currently not really relevant, the amount of versions that allow you to have different names is so low it's easier to just carry on saying the names need to be the same ¯_(ツ)_/¯
why they are different? i never named it like in the Inspector
you said that the file name and the class name need to be the same which is not true in newer unity versions
since i said that
that they dont need to match, no drama lol
so yes it is relevant, cause if they are using newer unity versions, what you said is not correct
Open the folder in explorer and make sure there are no duplicate files
but ofc it's good to always have same file and class name
the file name doesn't match the class name either (first letter isn't upper case)
@calm hull is your IDE configured?
i mean whatever IDE you're using
!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)
let me check thanks
I still think it's weird they did that . . .
it is 🤷
yes, no need to re-install
oh i see i never programmed in cs
only c++
lol
need everything
yesss
works now
thanks guys!
i was using the script and not the button in the gameobject
Hey guys, is this the right way to declare a TextMeshPro ?
No wonder I can't drag the GO in the thingy
TMP_Text is best to use
public TMP_Text variable; ?
Give it a try . . .
Why would the syntax differ? 🤔
other question, imagine a want to do a rpg turn game, where you have 4 characters. Im trying to do the campaign with 10 levels each level different scenery and different enemies. Should i do a general combat scene and depending on the level code the variants of i should maek one scene per level?
i'd go with one scene loading proper data for that level from scriptable object for example
imagine having 100 levels
TextMeshPro is the world-space version, TextMeshProUGUI is the UI version. TMP_Text is the base class for both
Wooahahahf
Hey, i wanna run the array from the first element to the last element and then return to the first element
How to do this ?
when are you going to learn correct terminology?
english?
I'm sorry :((((
don't be childlish please
run the array ?
what
Yeah yeah ...
but why do you need to loop
Silly me
for (int i = 0; i < n.length; i++) {
show(array[i]);
if(i == n.length) {
i = 0;
}
}Like this ?
what are you trying to do exactly
you realize that i is an integer..
so wrap that in a while loop to repeat it
pretty sure that will be a infinite loop
nvm if(i == n.length)
while (condition) for () { }
that's never true
not even explained use case 🤷♂️
So I have a shop UI, I wanna go through all the items, from the first item to the last item and then next to the last item, we'll see the first item
Look up while loops and foreach loops. Wrap a foreach loop in a while loop, or wrap a normal for-loop in a while loop. Note that this acts as a recursive method and without a proper way to break or delay the operation your program will crash.
Like a ring you know ?
why?
It just crashed :)))

🙂
so arent you scrolling through the shop UI instead of it rotating on its own
you probbaly want to wrap it with %
What you could also do is implementing IEnumerable
Yes I do have a Input.GetKey to scroll through
Because then you can iterate the list every time you near the end
It sounds like you want virtual scrolling
use modulus then, scrolling through forward
currentIndex = (currentIndex + 1) % array.Length;
if you want wrap backwards its :
currentIndex = (currentIndex - 1 + array.Length) % array.Length;
this will "warp" back to first item
Coding is scary
I'm obsessed, I can't control myself.
It's kinda spammy tbh
Ok sorry, I'll control it
Is subscribing to events on update bad practice?
I have this EnemyAI script which sets the _isProvoked. I also have another script attached to enemy that handles the damage take. I fire off an event on damage take and subscribe to it on my EnemyAI. I did not know where else I could do that and put it in update. https://hatebin.com/ugwqtwfapo
typical places are sun OnEnable/OnDisable for unsub
you only need to sub to events once, no need for multiple frames to do it 
I am just trying to learn how events work so yeah
tie an actual function instead of using anonym imo
🙂
Nothing like learning by breaking your editor
It works but something felt off 😄
I can do an actual function yes
how can i get rid of this?
in terms of bad practice it's up there with infinite loops, so yes
private void OnEnable() { EnemyHealth.OnDamageTaken += DamageTaken;}
private void OnDisable() { EnemyHealth.OnDamageTaken -= DamageTaken;}
I would guess you have a git folder pointing to nothing, or something
This isn't a coding question anyway #🔎┃find-a-channel
Did you check the docs for those?
I should do that. Thanks for the answers.
EnemyHealth.OnDamageTaken looks like a static event. So it looks like all enemies will become provoked if any of them are damaged.
good point
Ahh
Okay wow thats all good now. Thanks again.
I cannot unsubscribe if I use anonymous methods right? or am i missing something
Nope
It works by reference and anonymous stuff has none unless you store it in a variable
It's generally better to just write a method for it
Makes sense. Thanks
In javascript, I usually do console.log([object1, object2]) is there something similar in unity/c#? I'm aware of Debug.Log() but it seems a bit limited to just string (or maybe I'm just using it wrong?)
typically, it's used to output string messages, but you can log anything . . .
ah ok, but I can't do Debug.Log([object1, object2]) right? because that would be GameObject[] instead of a singular object?
array is still an object
it wont print the elements but the array itself
loop the array and log each element . . .
I was trying to debug line 21, figured I was going to do 1 Debug.Log() for both portal and gameObject for convenience
btw using names is bad practice
terrible practice
you're in a type-safety language, use it to your advantage
you can output multiple values in one log statement . . .
Then how would I ensure that a player is the one colliding and not an enemy? Use .tag instead?
components
You can just do
Debug.Log($"Portal: {portal.gameObject.name} | This: {gameObject.name}");
And use .CompareTag() instead of names. (or components as Xaxup said)
components give you more control over tags
TryGetComponent and you have reference to the instance already
with tags you need to compare, then get the component
gets messy
yeah who wants to sit there make a new tag each time
i very rarely use tags
You can use the name, but currently you can make the slightest typo or casing mistake and it will fail. Not to mention there's no clear indication what components check for this name. If you really want to use a name, consider using a constant string variable, and/or .Equals() using case-insensitive comparison
String comparison will always be slow though, even with these changes
https://docs.unity3d.com/ScriptReference/Component.TryGetComponent.html I'm reading this, so what would be type ? Would it be GameObject?
whatever you want
What have I done wrong?
if(collider.TryGetComponent(out Player player))
{
Debug.Log("collider has Player component");
}
Don't use GameObject, it's too generic.. everything in the scene is a GameObject. You want to TryGetComponent on something unique to the object you're looking to actually get
if the player has a Player component, you can use that. use a component that the GameObject should have attached to it . . .
that will only print if your collider hsa Player component on it
and you can acess instance of that player
player.healthSystem etc
Anyone?
chill man
give people time, you posted barely one minute ago . . .
don't post snippets, post !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.
your code screenshot doesn't show enough information, but you've put something outside of the class that can't be outside the class
also, post the entire class as the snippet doesn't help because there isn't enough information. make sure your IDE is configured; you should see red squiggly lines in your code. you have fields or methods located in the namespace —outside of the class . . .
it is not configured
Configure your !ide before asking questions here
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
• Other/None
After that the error is clear
so the type for the TryGetComponent would be the component's name? in this case would be PlayerController right?
It's the name of the class, which should be reflected by that yes
Component = class
that is the type. when you create a class derived from MonoBehaviour, it becomes a Component . . .
only Components can attach to GameObjects . . .
ah nice! I got it working with components Debug.Log($"IsPlayer: {collider.gameObject.TryGetComponent(out PlayerController _) }");
thank you!
You could also change it to out _
I can? I thought I need out PlayerController _
three is not point to try get component if you are not using the out paramater
Not sure why the type is needed here
also it needs the type because its a generic method
so you need to provide the type on the out, or provide it after the method name in the <T> area
Ohhhhh he doesn't have the generic type parameter
Right, add that and then it's not required
it can infer the generic paramater if there is a type in the args
if you use TryGetComponent<PlayerController> it should work . . .
yup
but no type from _
I'm blind
how can you tell he is not using it?
in the debug log he is not, but you dont see other part of the screenshot
that works
Good job team
but that just move the text from () to <> lol
instead of calling the same thing twice, store it in a variable
yea cache it
so that?
lol why _
but TryGetComponent is unnecessary for a log. instead, use it if you were using the variable . . .
also no you still wrote it TryGet twice
they mean cache the return of it
You might as well store the boolean call in a variable if you were to call TryGetComponent twice
Does Unity not have a ComponentExists method?
ah I think ya'll meant to cache the result of TryGetComponent and use that instead?
well looks like he is using a component as a tag
so might not need the data in the component but needs to know if it exists or not
bool IsPlayer = collider.gameObject.GetComponent<PlayerController>() != null;
well its till better than using != null
it's the same thing
its better to use try over that
i know Im saying if they need the component
yup
if you dont use the result of out then its not
also if just discarding you can declare it in line
try actually does not allocate if it finds nothing
right, but if it finds it does allocae the instance
ah I see, gotcha, so it's to save resources if I don't use that out?
so its no difference if you want to just check if a component exist
that only matters in the editor though
just learn what's out and TryGetComponent
Compared to GetComponent returning null? That seems wrong considering methods with an out parameter need to assign these parameters before exiting the method
if(collider.TryGetComponent(out TheComponent _)
this 👆, exactly what i said
if you just want to check if a component exist
no point of using TryGetComponent
and allocate the out result
thats why discard exists though
So GetComponent is probbaly just best here. Even if there was a difference in allocation I doubt it's fitting for #💻┃code-beginner
only in editor though..?
TryGetComponent attempts to retrieve the component of the given type. The notable difference compared to GameObject.GetComponent is that this method does not allocate in the Editor when the requested component does not exist.
what
You're still assigning the parameter in the method
how is allocation onyl related to editor?
So how does this save allocation
either way find it odd wanting to check for the existence without wanting the reference to the component
umm, how is that related kinda
GetComponent returns a normal null in builds, it doesn't allocate anything
in Editor it creates a fancy object for nicer errors, blabla
yes, one will not allocate in the editor
yeah did not realize is a editor vs build thing, but difference is the cost of the UnityEnigne.Object wrapper for a native object
also - no one cares, unless they're running Unity on a toaster, so 🤷♂️
idk maybe I was under the impression discard having relevance to allocation
well you are still assigning the parameter
to null
which is a reference type, so essentially just a pointer no more expensive then assinging a int
the cost is the thing the reference points to not the reference
For your information, TryGetComponent still allocates for returning a variable, even if the component does not exist.
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Scripting/GameObject.bindings.cs#L179C53-L179C62
So this does not at all make a difference in terms of performance, even if the result is null
TryGetComponent is faster in the editor than GetComponent - that's the main difference
which is no difference between just GetComponent<> != null lol
Go make a benchmark if that's the case, and return with the results
the main difference is speed in the editor . . .
am at work, can't be bothered, but that's the main point of it
but you are talking about totalyl different thing
in Editor, it wouldn't need to allocate... in build they're the same, just slightly different
than we are
no one said anything about editor
and you started some editor performance dicussion
in build it doesn't matter much
use whichever one you prefer in terms of code style 🤷♂️
we are talking about allocation, and that if you just want to check if a comopnent exist, it is better to use GetComponent instead of TryGetComponent
why?
idk scroll up
neither is allocating in builds
Should there be something in this code that reveals an allocation? I don't see it.
why are we even still talking about this, i incorrectly brought up a behaviour of it i thought was not only editor only and discovered it was after reading docs
I define allocating as getting new heap memory - neither Get nor TryGet does that in builds
different question than that GetComponent this time, I had SpawnEnemy() but now I want to pass in a difficulty level, but nameof() won't take a parameter right?
Either way the method is literally the same apart from that one returns a boolean and an out parameter, and the other one returns the parameter without the boolean. There is no difference except convenience
use coroutines
they're better, you can pass parmaters
yes and this is exactly the point of discussion
that there is no difference
and they said it's better to use try over that
better is subjective here
didn't sound subjective
I prefere typing TryGet even when using _ and dont need component
I don't, so are we even now in terms of what is better?
I prefer != null, but that's because I'm used to it from before the TryGet time 😄
exactly
would use a coroutine in this case, then you can pass what ever args you need
correct
its preference at this point
just realized that I have Start() and Awake() just use 1 or the other right?
with a coroutine you do not need to use nameof and really should not, can just call it in the start coroutine
both are for different purposes
StartCouroutine(SpawnEnemy(2));
and thats not a good way to start a coroutine
still annoying that Unity has string as default return when you generated a method from StartCoroutine 🤜 
use both if you need both.
Awake for getting all refences/ etc
Start for initiliazation with the references/ etc
not sure what you are referring to?
it's telling me to use nameof instead of a string literal
they both have different uses. use them if needed . . .
dont use strings at all
you call it
StartCoroutine(SpawnEnemy(0))
oh i meant like in VS when you generated a new method from StartCoroutine(MyMethod)), it defaults to string instead of IEnumerator. Sorry weird rant lol
like this
#💻┃code-beginner message
that wont work
ah have not used VS in a very long time
he doesnt have 2 parameters in his function
man you should really do some basic c# course
StartCoroutine(SpawnEnemy(0));
look at the example i am calling it StartCoroutine(SpawnEnemey(0));
where the ()s are matter alot
That's what I was going to do but someone says to use the comma
who said that
you edited that message...
noone said that
You should know that 2 params (using the ,) was wrong because the method you're trying to call only has 1 param
I know you're a beginner, this is something very basic. Don't blindly copy from elsewhere, think about if the suggestion fits with what you have
more or less your IEnumerator method is called with what ever args it needs then start coroutine runs on its returned value
Sorry, I should've known better since I wouldn't do that in javascript either 😦
Is there a way to see the collider that character controller has?
enable gizmos
also not code related
It's a capsule, should be visible. and this isn't a code question
oh yeah right sorry
How to understand the language
learn
take courses? some resources pinned in this channel
Ok
So if I understood coroutine correctly is that you can pause/resume it. Which means, I can "pause" the spawner when the player meets a condition, increment the difficulty, and the resume the coroutine to spawn different enemies right?
always suprised people ask such question
no
Or does the coroutine needs to be reset to apply the new difficulty value?
you can not pause, but you can stop and restart them at will
ah, I see
to do that you need to save the return of StartCorutine so you have a handle to it
and can later call StopCoroutine on that handle
Although could technically pause a coroutine if you use a while loop inside
well yeah cool set a bool, and have it just yield frames
Can anyone help me with TextMeshPro text not been set?
using System;
using Photon.Pun;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
// I have the public class and stuff just not included
public TextMeshPro damageIndicatorText;
public GameObject damageIndicatorParent;
// Inside some other code I have the
// SetDamageIndicator(25);
void SetDamageIndicator(int damageValue)
{
Debug.Log(damageValue);
damageIndicatorText.text = "Damage";
Debug.Log("Animating damage indicator.");
}
It Debugs the correct Number but the text Is never getting set like to anything
though if you want something running for the applications life time you turn on and off. personally i would just use the Update method
and keep track of deltaTime
TextMeshPro is for the 3d TMP, not UI
TextMeshPro pretty sure thats not a proper type for 2d
use TMP_Text
So i need to use TMP_text for
head tags and stuff?
damageIndicatorText.text = "Damage"; do you want it to just say Damage ?
so hoping for just floating worldspace text, or got a worldspace canvas for it?
It should say the Provided Int but it wasn't so i just set to a string to see if it was the int breaking it
damageIndicatorText.text = damageValue.ToString();
Is the ref assigned in the inspector?
I tried that with the code provided and it was no errors anything and was just not setting
pretty sure foo is right here
Huh?
though you would get a nullref in that case
I set it inside the script / inspector
do you get the Debug.Logs?
Ye they work
did you try it with TMP_Text as the type
You're gonna need to do a screen recording and show us what's happening, we're just poking around in the dark
25
UnityEngine.Debug:Log (object)
GunController:SetDamageIndicator (int) (at Assets/Scripts/GunController.cs:179)
GunController:Fire () (at Assets/Scripts/GunController.cs:164)
GunController:Update () (at Assets/Scripts/GunController.cs:95)
Ye just tried that
also are you calling the code on the right object
won't make a difference changing the type
are you calling it on your prefab instead of the intance of it
Since no errors feels like it's not executing where you think it is
Makes even more weird as I have attempted with the name tags
The name tags code works fine and I tried making the Damage indicators code the same and it was the same and still would not show the text as damage
Like the Nametags, is the same as the Damage but the nametags work for some reason
so the guncontroller references the dmg text on itself.. which seems wrong
It's gonna update the text above you, when damaging the enemy
So, if you have the scene view and game view visable at the same time, I bet when you do damage, it works.. but not on the tmp you expected
Ah I get you
Yes it does and i feel dumb asf
we've all been there
Anyone know how I can implement a schedule system for this school rpg im makinng?
As of now I have prefabs of npcs in different groups, i then assign a location for each group if that makes sense
Hi guys,when 2 objects collide how can i disable the vincolar reaction between the 2 objects?
like let's say the 2 objects collide,object1 adds a force on object2
but object2 doesn't add a force to object1
Not really sure best place to ask this, as I couldn't see a PlasticSCM channel.
Every time I hit play, my render textures are changed, and this change means PlasticSCM is constantly wanting me to check in the changes.
I'm not sure what the recommended solution to this is? Is it to do with ignoring, or hiding, those changes? Or something else entirely?
Like having a particle system that sends just one burst and calling it from script?
I think the only thing I can do is start playing or start playing from X position, no start a specific burst
There's this https://docs.unity3d.com/ScriptReference/ParticleSystem.EmissionModule.SetBursts.html and SetBurst
You have full control over what you commit. Just don't select the render texture?
Hi all, I'm trying to load an image located on another disk to a Texture2D to be used in an image visual element as part an editor window, and I'm trying to use ImageConversion.LoadImage. When I debug log the file path it outputs correctly with the file path of the image, however when I use the LoadImage function I get a directory not found error. The weird thing is that the error log outputs a path which has the project path appended onto the image path for some reason. Anyone got any ideas on why this is or how to fix?
because LoadImage expects a path which is within the current project path
So .SetBurst is basically just like setting it on the burst property of the particle system and I can sync the audio from there...
Oh ok, I'll look around for a different method then. Cheers.
The file:// protocol is not recognized by System.IO. It's used in URIs. You probably got that from code loading local files through UnityWebRequest.
I mean, is not much different of setting it manually from an animator that plays sound of something like that, but would have to do
why is your path using the file protocol?
That's likely because I'm using a package to interface with OpenAI and grabbing the result
remove the file:// from the front of the path and it should work. fyi file protcol is, correctly, file:///
ok that makes sense, i totally glossed over the file:// at the start and assumed the path was correct cause it downloaded correctly
bit stupid of me
it looks like you should be using Application.persistentDataPath anyway
is that what I should be using for external files?
apologies for my ignorance but that looks like it references a separate specific folder, the images are being generated in their own specific folder and i just need to load the currently generated image without moving it, your suggestion seems like when the images are generated i will need to move them into wherever Application.persistentDataPath points to
yes, Application.persistentDataPath is the ONLY place where you are guaranteed to have both read and write access for data files
Oh ok, is there no other reliable way to be able to read data outside of the project except for using Application.persistentDataPath?
reading you can use UnityWebRequest
I've seen some suggestions on using unitywebrequest on the forums
but writing you should only use Application.persistentDataPath
I don't want to alter the generated image I just want to read it and slap it onto a texture
so im guessing unitywebrequest is the way to go
tbh it looks like it's in Application.persistentDataPath anyway
it is
🤦♂️
if Application.persistantDataPath returns the directory location though how can I get the specific file I want
if it returns the full path the Path class has methods for splitting it up
I guess result is coming from somewhere
yeah result comes from the generation request
then you'll probably be ok with just stripping off the file:// from the front
application.persistantdatapath returns the correct folder it references in the documentation, mine being AT2, but I need to access a folder within called download_cache and then the current result
Why is my character not falling here? The terrain has a one way platformer collider. All other normal terrain behaves properly
Path.Combine @latent zodiac
check the collider . . .
How do I reference my navigation modifier through code?
oh so I can use Application.persistantDataPath and combine it with the folder name and the file name of the result?
I want code changing it from walkable to unwalkble
yes
saveFilePath = Application.persistentDataPath + "/saveData.bg"; i have this for example
as you can see the collider is traced around desired area
ok cool. that seems easy enough, just need to remove everything before DownloadCache in the path stored in result
ill give it a shot, much thanks for the help @languid spire @rare basin
What about the collider for the character
and the other one?
ok unfortunately the file path is very similar but not the same. Application.PersistentDataPath points to C:\Users<user>\AppData\LocalLow<company name> but the generated images are being stored in C:\Users<user>\AppData\Local\Temp\
this is surprisingly way more annoying than I thought it would be sheesh
+ "../../Local/Temp"
then that is not going to work in a Build only in the Editor
then I think stripping the file:// is your best bet
i still run into the issue of not being able to load external files right? cause i cant use ImageConversion.LoadImage cause it needs to be in the project directory and I cant use texture.LoadImage or something like that either
no you are good, it is the file protocol that wants to be in the projects folder not the File.ReadAllBytes
ok that worked wonderfully
all that time i spent just because of the file:// in front of the path, crazy how I missed that
thanks again @languid spire , knowledge and guidance is very appreciated
not enough time learning front end Web Dev
ye thats foreign territory to me if it wasnt obvious
np, lesson learned I hope
learned a fair bit today 🙏
excellent, then my job is done
You don't. You put a semicolon at the end of line 22. And since whitespace is ignored, you can put that on line 23
This is perfectly valid C# syntax:
Debug
.
Log
(
"Hello world"
)
;
As long as you aren't splitting a symbol, C# doesn't care how many lines your one statement spans
Is something like this okay? Where I have a static instance of a Monobehaviour object to be referenced by outside scripts?
public class Person : MonoBehaviour
{
public static Person UnknownPerson { get; private set; } = new Person();
string fullName = "";
int age;
private void Awake()
{
if(UnknownPerson.name == "")
{
UnknownPerson.name = "Unknown";
}
}
}
You cannot use new to create a MonoBehaviour
But other than that, this is basically a singleton. Usually it'd also be on a DDOL object and have some guard clause to prevent creating a second one, but that's fairly a common design pattern in Unity:
https://gamedevbeginner.com/singletons-in-unity-the-right-way/
this basically a Singleton pattern, use it
You've essentially made a Single-Scene Singleton
if it only ever needs to exist in one scene, it's fine as-is (once you remove the invalid default value for UnknownPerson)
I don't want Person to be a singleton though. I just want to provide global access to a specific instance of Person
Yeah, single scene
that is what a Singleton is
Any way to get UnknownPerson to exist at compile time?
In case I want other classes to have access to it?
Say my family class has a person isntance. I want that person instance to start as UnknownPerson
private void Awake()
{
if (UnknownPerson == null) {
UnknownPerson = AddComponent<Person>();
UnknownPerson.name = "Unknown";
}
}
hey y'all, who's familiar with Behaviour Tree, Behaviour designer in unity, i need help
So does that component just get added to the first instance of person that calls Awake?
yes
{
if (other.gameObject.layer == LayerMask.NameToLayer("Environment"))
{
Debug.Log("Test");
Destroy(gameObject);
}
}```
Hey guys do layer checks not work within OnTriggerEnter
I even did a public Layer myLayer and still doesnt seem to detect it
Hmm. K. Not sure I love that. I'll mess around with it
is OnTriggerEnter even being called?
100%
i have another check for player
works fine
in that case debug the gameObject.layer
Hey. Its me again T_T... I have this script here and it works zooming in and out. But it is zooming in and out too fast. I tried to lerp but nothing seemed to have changed. I read the documentation but did not understand..https://hatebin.com/tioqekaihg help me pls.
Anyone knows what could it mean ?(the last errors, i think the warning are just linked to that) but the Error seems a bit obscure when i doubleclick on it it leds me to "edge.cs" and i don't know what it is
Seems linked to that "localScale" part
You’ve referenced a gameobject in your code but not actually dragged it into the reference
unity editor bug, restart unity
Oh?
Yeah Thats in the UnityEditor Namespace meaning its a Unity side error
At the very least the NodeGraph one
Just restart Unit yand it should fix itself
the other ones are likely actual warnings
that, generally, changing scripts whilst in Play mode
Ok i restart and tell you
public void Update()
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 10f))
{
Debug.Log(hit.collider.name);
Vector3? closestPoint = null;
if (hit.collider == gameCollider)
{
if (SnapToValidPoint(hit.point, out closestPoint) && closestPoint != null)
{
highlighter.transform.position = (Vector3)closestPoint;
}
}
}
}
private bool SnapToValidPoint(Vector3 collisonPoint, out Vector3? _closestPoint)
{
Vector3 cachedPoint = Vector3.one * Mathf.Infinity;
bool foundSnappablePoint = false;
foreach (var thing in placementGrids)
{
for (int x = 0; x < thing.gridWidth; x++)
{
for (int y = 0; y < thing.gridHeight; y++)
{
if (Vector3.Distance(collisonPoint, thing.playPositions[x, y].position) < Vector3.Distance(cachedPoint, thing.playPositions[x, y].position) )
{
cachedPoint = thing.playPositions[x, y].position;
foundSnappablePoint = true;
}
}
}
}
if ( foundSnappablePoint ) { _closestPoint = cachedPoint; return true; } else { _closestPoint = null; return false; }
}
Any ideas as to why the snapping is so jank?
I get that error when i a script was on a gameobject and then i delete a script or change the name of it
Hello, can I ask some help?
https://discussions.unity.com/t/problem-creating-a-gameobject-radius-when-i-trigger-a-button/338689
Hello, I’m new to this group and a beginner in using Unity 2D. I have a problem: I can’t create a circular bullet that increases its radius when I press a key button and gets destroyed when it reaches the maximum radius or size. here my codes: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Inp...
What is the code doing as its written? Error or?
Hi guys,when 2 objects collide and they are all dynamic objects how can i do that the collision of the 2 objects in calculated just via script?
like let's say that the player1 moves and hit player2,i don't want that unity3d calculate the collision between the 2 objects by default
what do you want to happen?
stop there. Ctrl+Enter is a thing
let's say that player1 has a mass of 1kg and player2 0.01kg,i don't want that if player1 has a velocity when it hit player2 player2 moves if there is not a script who control the force that player2 has to receive
ok, once again you say what you dont want, now read my question again
ok when player1 hit player2 i want to move player2 just via script using a force
is player 2 kinematic?
no