#💻┃code-beginner
1 messages · Page 33 of 1
I'd rename SetDurability to something else, since it does way more than just setting the durability
Something like UpdateDurability
Properties must be in PascalCase
Won't fix the error, but at least the naming conventions are applied
Those aren't properties, those are variables.
Errors, these are fields in your class, not properties
[field: SerializeField] public float Durability { get; set; } -- pretty much the same as in the interface decl
so how do i know how you sset this up ?
provides no context then asks for help . A+ kid
then insult help
smart
w/e fuck this..
one last thing
i cant have a header
Target the field too :)
go drink a glass of milk kiddo
can anyone dm i need help with starting to code simple player movement
I, uh, need a little help with - same
what is bro yapping about
Idk must be projecting
God the discussion quality just dropped so low it underflowed
<@&502884371011731486>
its just sum little kid
!mute 470339223401136149
ollywanted77 was muted.
@queen adder + @broken hazel - Ask here. Read the #854851968446365696 for instructions on how to ask a proper question here. No DMs, conversations are always 100% here for everyone to see and chip in if they want
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
is there any way to default it to 100?
like durability and max durability
on default
= 100
Sry
i didnt know they were so useful
That's also compiler trickery, the value gets put on the backing field like the attributes. Most of modern C# is compiler trickery and syntax sugar nowadays
Switch expressions? Compiles to a bunch of if statements
etc.
Can some help me with character controls? I've look some up before but they were only allowing me to look in one direction. I believe this is how I ask
rigidbody or character controller
dm me
you're going to need to provide a lot more information.
It won't let me DM you
accept friend request
Camera Rotation isnt clamped to Time.deltaTime
What on earth does this mean?
YOu have to show code
but yeah that was a really weird way of saying "my code is framerate dependent, help"
this is good and fine
there is no need for deltaTime here
mouse input is already framerate independent
adding deltaTime in this calculation would be erroneous
how do i make a formula to calculate the amount i need to add to the break percentage?
durableItem.BreakPercentage += Random.Range(12.5f, 25f);
like for example my ak has 100 MaxDurability and the Durability can go between max and 0
like i want it to add more to the break percentage the more then item is broken
so the lower Durability the more to add to BreakPercentage
did this
durableItem.BreakPercentage += (durableItem.MaxDurability - durableItem.Durability) / durableItem.MaxDurability * 35;
this is python..
whoops wrong discord lol sorry
If I want to make a sphere grow over 2 seconds smoothly how do I go about that within a coroutine?
just add the amount while timer seconds is less than 2
for (float t = 0; t < 2; t += Time.deltaTime)
{
// Size Lerp here with progress being t / 2
yield return null;
}```
timer = 2f;
currentTime= 0;
while( currentTIme < timer){
//scale sphere
currentTime+= Time.deltaTime
yield return null;}
Okay thank you, these helped a lot
interesting, i forget for loops are like similiar to while loop but with iterator xD
they used to frighten me lol but they're quite powerful to do retries and stuff
scary while loops 👻
basically a for loop, but you declare and update everything out of the () scope
well, you could update within () but that's just weird
Anyways, caesar out, time for some programming dreams
so i have it to my player can eat objects to get bigger but the camera doesnt get further away or anything so the player fills up the whole screen how do i fix this
there should be an offset component
i cant find one
Double for each is a good use case.
But use for loops instead for that.
for ((IEnumerator a, IEnumerator b) = (_a.GetEnumerator, _b.GetEnumerator); a.MoveNext() && b.MoveNext; )

I use tupples to declare multiple stuff in a for loop too often. 
im using the cinemachine freelock
how do i change that via a script
store a reference to the CinemachineCameraOffset and modify it
void ChangeOffset(float sumValue)
{
var offsetComponent = cmvirtualcamera.GetComponent<CinemachineCameraOffset>();
offsetComponent.m_Offset = new Vector3(0, 0, sumValue);
}
yeah just store it
since ull change it often
its an example.. the parameter is in the method, wouldn't hurt if you did some refresh on c#
yeah i gotta do a refresh tutorial lol
so what do i set it to
have you tried actually testing values on the offset component at runtime to know which values u need?
forget the code right now
in playmode, change the offset in the inspector
on the component
yeah i did that
ok so which Z value looks fine when you have big sphere?
hi so i recentley created an organization with my friend and i made a project how do i get him on it
just make sure u store the reference so you don't get it everytime u change value
this is not a code question
would this not work. just changing the offset plus the variable
wdym plus the variable
sorry to bother you but i only got like 20 minutes so how would i do this?
How do I ensure that the script for my object does not affect his childrens except for one specific?
cinemachineOffset.m_Offset = new Vector3(0, 0, -sphere.transform.localScale.magnitude) ;
where do i put that
Just don't touch any objects aside from the one you do want to affect.
which are variables?
the ones that error says don't exist..
so for the first one should this be the variable
public CinemachineVirtualCamera cinemachineOffset;
no CinemachineVirtualCamera is not the right component
think back to which one you're trying to change..
you probably want an additional parameter to adjust the offset
incase magnitude alone will create too much of prefix distance
[SerializeField] private float offset = 0.2f; // try different values, positive value = closer to sphere
cinemachineOffset.m_Offset = new Vector3(0, 0, -sphere.transform.localScale.magnitude + offset) ;
@amber spruce
so for some reason the more it gets bigger it makes it so you cant move the angle your looking at higher so you end up looking threough the ground
you'd need to add a Cinemachine collider
mind you this isn't the way to do, just a way to do it. for Free Look it gets more tricky too
i cant find a camera collider is there one or do i make my own
its a cinemachine component
*Extension
still ends up being like this
what am i looking at
my camera cant go further from that so i cant look straight
i was talking about the rig
this??
you have to play around in playmode with settings that make most sense while the ball is big
aight
what would be stopping me from looking up is there something stopping the y rotations
you can change the rotation here
as you change that you have to change the height/radius on rig
play with the values until its correct
so like i cant just keep looking up thats my problem
that changes the rotation doesnt stop me from going to high
can u record vid how it looks like
im tryig to build the facepunch.steamworks
and it just :(
anyone know how I fix this
i cant look any further up
normally its fine
but when i get big it aint
maybe instead of offset change size of rig with the same value
yeah I think that will work better..
remove the FollowOffset
try this instead
freelook.m_Orbits[0].m_Radius = sphere.transform.localScale.magnitude + offsetTop;
freelook.m_Orbits[1].m_Radius = sphere.transform.localScale.magnitude + offsetMid;
freelook.m_Orbits[2].m_Radius = sphere.transform.localScale.magnitude + offsetBottom;```
Dipping my toes into how Matrices work and stuff and think just some names are throwing me off
If I set an objects Gizmos.matrix to transform.localToWorldMatrix or transform.worldToLocalMatrix. Is that literally just the same of having it's origin be based on the objects local and world values straight up? the names of the properties had me wondering if theres anything else being added but I just need someone smarter than me to clarify ❤️
that?
no the component you added..
CinemachineCameraOffset
this clips you through the floor
so that
ye
what do i put for freelook and offsetbottom, mid, and top
Is it okay to use Destroy.() for collecting ammunition?
smth like this for the variables im missing
public CinemachineFreeLook freelook;
public float offsetBottom = 0.2f;
public float offsetMid = 0.2f;
public float offsetTop = 0.2f;
yes
freelook.m_Orbits[0].m_Radius = sphere.transform.localScale.magnitude + offsetTop;
freelook.m_Orbits[1].m_Radius = sphere.transform.localScale.magnitude + offsetMid;
freelook.m_Orbits[2].m_Radius = sphere.transform.localScale.magnitude + offsetBottom;```
the order is reversed tho, i edited old msg
wdym by collecting ?
Collecting any gameobjects
as long as they're not stored in a list sure
destroying and instantiating comes at a cost, ideally you want to re-use the same objects with pooling
Interesting
Why would you want to use a list?
Is that when all the items are the same?
idk if you collect something and it stores in a list, if you destroy it just becomes "Missing" in the list
like if you have collectables or something
Oh, okay
so now its same problem as before it still is way to close
so increase offset
you had me get rid of offset though
is putting all events from all scripts in one dedicated mega events script anyone can run/subscribe a thing cause im boutta do it to eradicate some macaroni
changing them doesnt do anything'
are you changing it in the code or inspector ?
inspector
select the camera and screenshot the gizmos in playmode
I'm getting an error and I'm not entirely sure why, maybe someone can point me into the right direction? I have a script added to a game object as a component, that script has an empty array in it. When I try to change the size of the array in the inspector, it completely removes the array and the ability to change the size of it and a wall of text comes up in the console starting with "NullReferenceException: SerializedObject of SerializedProperty has been Disposed."
I can put the rest of it in a pastebin if more is needed
are you in 2022
yes i am
Also, it may make a difference, I'm trying to edit it on a prefab, not in any scene
Hm, it seems to work if I open the prefab and not just click on it once in the project folder
2022 is buggy af
i get spammed with those on 2022.3.3
try to update to latest patch if you're not on it
I think its 11 but for me it fixed those errors at least, hmm not sure maybe its a script?
It's giving me references to other scripts like "UnityEditor.SerializedProperty.get_intValue () (at /Users/bokken/build/output/unity/unity/Editor/Mono/SerializedProperty.bindings.cs:996)"
and when I click on it to inspect it, it opens up and there's nothing in there
It was working fine until like 10 minutes ago
do you have version control installed?
try removing it
or restat unity / default layout
I tried to change an array to be able to use nested arrays, when I declared the variable I used [][] instead of just [] and it went up in flames
ohhh
Then when I changed it back to just [], it's still giving me issues
I installed version control but I haven't done anything with it yet unfortunately
the only strange thing about this is unity doesn't serialize [][]
but I don't know if it would blow up like that just changing it once array was serialized
It removed the elements entirely and I figured "ok i guess it doesn't work like that", changed the script back and now it's doing this lmao
just tried it and it doesn't blow up for me
I may have to try changing the editor version then
why when i set a float to "0.8f" it becomes "0.800000011920929"
oh i forgot I also tried to do [ , ] as well thinking it would do the same thing
this is normal for floating point numbers to do
right but how do i make it actually 0.8
you dont
you could try using double instead of float
why
0.800000011920929 is greater than 0.8
what are you actually trying to achieve
when i compare the variable to 0.8f it says the variable is greater, i need it to not do that
let me guess, you're trying to use == with floats?
yeah
Math.Round(yourNumber, 1) will round it to the nearest tenth
yeah that's your problem. use Mathf.Approximately when comparing floats
Also that
floats can almost never be exact so == bad
but why is a variable i set to 0.8f different to 0.8f
weird comparison but imagine if you bought a box of cereal that said it had 8000 pieces in it and you counted them all. it's probably around the 8000 mark but it's more than likely higher or lower just because of how the cereal machine fills the box
and the crumbs. those are parts of pieces
and the inaccuracies in floats are like the crumbs
Imagine you had 100 index cards to write every number between 1 and 1000. You can't give each card its own number, so you put some of the commonly used numbers on the cards and accept that if someone picks something else, they're gonna get "close enough"
i have to rewrite my scripts because 0.8 =/= 0.8
If someone asks for 84 and your closest card is 85, if they handed someone their 85 and said "hey is this equal to 84?" the answer would be "no"
Note that this is not about c# or unity or anything. It is inherent in computers
0.8 equals 0.8, but 0.8f does not necessarily equal 0.8f
Yep. Never do == with floats/doubles/etc
just use Mathf.Approximately
public static bool Approximately(float a, float b)
{
return Abs(b - a) < Max(1E-06f * Max(Abs(a), Abs(b)), Epsilon * 8f);
}```
🙂 behind the scenes the magic
whats the thing for <= and >=
<= and >=
if firstValue is greater than secondValue or firstValue is equal to secondValue
it's two checks built into one for convenience 😄
no for floats
Those are fine to do with floats as is. There is no other thing
<= and >=
what
Floating point imprecisions means they won't be exactly equal 🤷♂️
But less than and greater than can be easily checked. Why would there be anything else?
but if i do var <= 0.8 and var is 0.800000011920929 it will say its greater instead of equal
Yep.
so what is the <= version of approximately
There is none
<=
why don't you show your actual code if you are having a problem with your code
Perhaps start a thread too
theres no easy way to use Gizmos.DrawCube in a function outside of OnDrawGizmos or OnDrawGizmosSelected right
Nope
pain
I have a package that practically functions an expanded Debug.Draw, all wireframe though https://github.com/vertxxyz/Vertx.Debugging
Ooo I might peep this then
Actually if you have a sec, I don't really know how to articulate my issue without a massive text dump but tl;dr I'm trying to rotate a gizmos to reflect my transforms rotation but when I set the gizmos matrix to my transforms localmatrix the drawing im trying to do is wrong because my positions im using already have the transform.localPosition baked in so its getting added twice.
currently i wanted to try and make a custom DrawCube function that basicially -='s my position so it like offsets it correctly but on the drawcube function side so i dont have to change my position directly
if that makes any lick of sense
You should set it to the transform's matrix and then work locally, so the position of the object is at Vector3.zero
I'm trying to do most stuff locally but I do need to consider world stuff for the game mechanic i'm trying to pull off aswell
I have a 3d tile matrix that I have "synced" to it's transform position but I want the parent of that object to be able to move and rotate aswell
lmao I tried changing it to the new version of the editor and it's still happening
is class holding all the events anyone can run and subscribe to a thing lol
I have this cute little 3d matrix here that stores all my tiles but this is going to end up being a cube like this so I can rotate and move the Planet's object that's in the center and have each face-child and their respective 3d matrix adjust correctly
forgive my terrible perspective drawing skills
next time show the error message
Is there any way for the Execute() to know who did the method call without putting my object as a parameter? Want to make things look generic
this is in my player class
considering the observer pattern
do you have the action in a different class from the one that is calling it ?
yes
and you want the action to have the information of which object did the call
yes
yeah im pretty sure the only way to do that is by passing the object as a parameter, but I dont see that being a problem in any way.
Maybe you're right. I was simply obssessing on trying to make it look clean
yeah i get what you mean, although what exactly are you trying to do ?
why do you need the action to know which class called it
the playerClass has an int damage and the UnitAction im currently executing is a Strike(target)
I just want it to look like player.doAction(new Strike(target))
simply adding the player to the parameter makes things much simpler tho lol
but where is the action ?
you could use the stacktrace from System.Diagnostics, although idk the purpose of this really
is that in a separate class ?
it looks something like this
Im trying to understand why you need to know which class called the action
yes it is in a separete class
and tested it like this
the book I'm following (that teaches about the command pattern) passes the doer of the action as well. I guess I'll just surrender and do that as well
if you really need to know where the action is being called then sure, but I dont know if this is the best way in general to approach what you are doing.
I want to make the Enemy Jump every 2 seconds however the enemy GameObject isn't doing that. What is wrong with my code?
Can't see any issue with the code.
Are there any errors?
Debug your code with logs or breakpoints.
A lot of the code has a yellow bar on the left (meaning unsaved). Have you saved it since adding the jump?
Yeah I have. I think an issue might be with my Waypoint Follower script. I think that may interfere with this script
If you are setting velocity in it, it will override the jump
This is my Waypoint Follower script I have for my Enemy. I do not see how this can interfere with the Enemy Jump Script
Even when I disable the Waypoint Follower, the Jump script still does not work
You are directly setting the transform in this script. Which is kinda like teleporting
which would probably interfere. But it doesn't affect velocity (teleporting doesn't impart velocity), so I dunno
Generally you don't wanna mix rigidbody and transform based movement.
It can work, but you gotta be careful.
Why does my healthbar prefab disappear when I zoom in too much?
Because it went behind the camera I assume
oh, didn't know that could happen
I'm an idiot. I forgot to add the Rigidbody2d Component
Ha, I was just about to say, "Wait, do you have a Rigidbod- wait where'd the video go?"
Good job getting it on your own though
It must've been throwing errors then.
i was gonna ask where it was as well before the vid was gone, you should also have your console open when going through issues. I suspect your console was throwing errors like crazy since the rb2d reference was gonna be null
This is my first Unity game so I have a lot to learn. I will check console more often thank you
is there a way to put Pose variables together? like Pose + Pose to merge the values?
your example is just how it works yeah
myValue = myValue + myOtherValue
adds your othervalue to your value, a shorter way of doing it is
myValue += myOtherValue
or if you want a new combination value
myCombinedValue = myValue + myOtherValue
What's a "Pose" variable?
i keep getting this error tho
What type is it?
As you can see in the operators section, there's no addition operator:
hmm okay
When a parent transform has rotation and a child transform changes its world rotation and world position to reflect that change, what is it actually doing calculation wise?
apply the same transformation matrix to all children
I don't understand what you mean by this
Position+rotation+scale are represented as a matrix internally. You can do some matrix math to rotate/move/scale objects. When a parent transform is changed, it's transformation matrix is recalculated and applied to all the children.
Or something like that.
Do you know what i'd want to look into if I want to do that myself?
I have a 3d array of positions and I want to apply my transforms values to them like each of them were children
you can learn the math but strongly suggest you dont recode the math yourself, you can learn how to use matrix4x4 etc
Oh yeah I have no desire to be like a super wizard nerd in this regard, my goal is just to re-create the end result
advice on utilising whats already there via matrix functions would be more than ideal
I've looked at this a few times over the last day or so and while I understand there are things I would want to use there. I don't have the math comprehension to put it together
you may get started with 2d and 3d vector and transformation math first
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)
how
By following the steps you see in the bot's message
ok
hey, followed a tutorial for a basic enemy ai, but it gets stuck on the edges of platforms. is there a simple fix for this?
maybe not edges of platforms specifically, but the edges of the mesh
Hard to say anything without more context.
what do you need
tutorial, script, what part the script fails
For some reason my Enemy Way Pointer Destroyer Script does not have a Checkboxto disable it. How can I fix that?
that means it has no unity messages that only run when it is enabled
in other words, disabling it will do literally nothing
But it would in my case
maybe it is requried by other component
It will prevent the enemy from freezing
This is the script
okay so disabling that will do literally nothing at all
When I remove the component the enemy does not die which is what I want. However I would prefer that to be in a enable/disable checkbox in case I want to add it back
nothing in this component is affected by whether it is enabled or not
https://www.youtube.com/watch?v=UjkSFoLxesw&ab_channel=Dave%2FGameDevelopment
everything set up like in the video except i have a lot of elevation changes. could i be that the enemy gets stuck when it tries to go somewhere that's a different elevation but cant figure out how to get there?
FULL 3D ENEMY AI in 6 MINUTES! || Unity Tutorial:
Today I made a quick tutorial about Enemy Ai in Unity, if you have any questions just write a comment, I'll try to answer as many as I can :D
Also, don't forget to subscribe and like if you enjoyed the video! :D
See you next time.
Links:
➤ NavMesh Components: https://github.com/Unity-Technologi...
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Hi all,
Sooooo, I'm trying to build a pretty simple vehicle controller and at the moment I'm a little stuck on suspension stuff. I have an Empty which is the suspension 'target' that I'm trying to raycast to the ground and then move the target to the hit.point, problem I'm facing is that the target object needs to be a child of the main vehicle body, but when it is, the raycast doesn't move the object. (if I unparent it, it works fine), I'm a little confused as to why the script isn't 'overriding' the position.
Can anyone see where I'm going wrong please?
public class SuspensionTargetVPosition : MonoBehaviour
{
[SerializeField] Transform targetWheel;
[SerializeField] float targetHeight;
// Update is called once per frame
void Update()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(-Vector3.up), out hit))
{
Debug.Log("I hit Something");
Vector3 groundIntersectPosition = hit.point;
transform.position = groundIntersectPosition;
}
}
}
Is there a suggested way to stop jitter in a character controller when it get's moved by other code and/or parent transform changes?
I have encountered a bit of a structuring problem, let's see if i can explain it so it makes sense. My player has a script called "PlayerGun". If the player runs into a gun he picks it up and the guns data get copied into that script and then that script handles shooting/rotation etc. Pretty simple. Now i have encountered a problem where my guns has been getting more complicated and i feel like my script holds unecessary methods for things they don't use. For example i now have guns that create bullets that check for collision and guns that create raycasts that check for collision. So I could split up the logic into abstract classes (PlayerGun -- PlayerGun_Bullets -- PlayerGun_Raycast). But then i would have to hot-swap between components on the player, depending on what type of gun they pick up. Probably need a script on the player that handles that hot swapping too. Is this a feasible thing to do?
I have a dashing code and it workes fine
However when I put the player at origin and dash it sometimes goes 3.2 units and sometimes 4.8
It's a fine solution. Another way to do it is to delegate the shooting logic to the specific item object instead.
How can I fix it?
Ignore the debug log
To fix it, first identify the source of the issue. Is your velocity always of the same magnitude?
Yeah
it's same
I can share my screen if you want
If it's the same, then the problem might be with you relying on time instead of fixed updates count within that time period. Might want to yield yield the next fixed update(or a few in a loop).
Might want to yield yield the next fixed update(or a few in a loop).
What do you mean by that? Can you explain it a bit?
It's likely what you're saying is right
Alright, awesome, thanks
I am unable to drag and drop an AudioSource clip into another gameobject, any idea as to why?
Check the API docs page for YieldInstruction.
That or avoid using a coroutine at all.
Hmm that didn't work too
Well, you still have the waitforseconds 😅
.
Yeah but if I remove it I can't control the dash duration
With time, no. But you can control it with fixed update frames count.
The issue is because you're trying to control the duration with time.
[SerializeField] what does this mean?
Maybe if you wait for the fixed update at the very beginning of the coroutine it might work, but if you ask me, that's still unreliable.@spare umbra
It means that the field should be serialized.
Just writing it won't serialize it, right? xd
It will. Just adding the attribute would serialize it. Just like a public field.
Assuming the object that the field belongs to is serialized as well.
So is it enough for me to just write it for the save system? an extra method or xml serialization etc. Don't I need to do it?
Depends on what you're using in your save system.
Hello, can someone tell me what is wrong on the underlined code and how to fix it ?
I don't use. That's what I'm trying to say. Do I need to write another save system or is it enough to write it at the beginning of the variable I want to save?
u cant use SetActive
Oh, what is the replacement of it then ?
use IsActive or Active
Of course. Save system is a whole separate system that you need to implement. The attribute just makes unity serialize the field.
!this.Flashlight.IsActive
or
!this.Flashlight.Active
okay thx
SetActive does not return anything, so you can't use it as a condition.
setactive is a void method. You cannot use void methods as condition xd
use this.
It says it's an obsolete way of saying it. But works nevermind.
!this.Flashlight.activeSelf
or
!this.Flashlight.activeInHierarchy
Yes, because that method was replaced with a new method. It is in the old method, but it is trying to say that you can also use the new method.
And what is the code to state if that a gameobject is unactive ?
false?
Alr
But I advise you to put a light on your flashlight object and make that light active. not the object itself.
Because if you close the object itself, you cannot use the object itself to open it back.
yep exactly.
If you disable the gemobject, you cannot use the scripts inside the gameobject to reactivate it. If you try to use it you will get an error.
And how come you could still reactive the game object with everything with it too, right ?
That's an option, I tried for other gameobjects and it worked.
You will get the error "Object reference not set to an instance of an object". or "null reference exception".
its like turning your bedroom ceiling light off vs turning the whole house power off
hmm I don't know. I got object reference when I tried it.
Disabled objects still exist. They're not destroyed. So you shouldn't get a null reference on an existing reference.
If you try to find it with one of the find functions, you might not be able to, this getting null. But that's a different case.
Shouldn't you not use that object and its content when you disable it? Do I remember wrong?
It may not be null reference, but I remember getting an object reference error when I tried to use disabled object.
Maybe my engine version is outdated, I'm not sure.
Basically, what I want is to toggle a gameobject, which is a flashlight. I would like to be able to toggle it on and off with the same key button.
No, it doesn't matter. You can use it. Although it makes little sense to disable it if you're using it.
Yes, that's what I mentioned with the find functions.
call method on script on a disable object is completely fine
The problem I had was something similar to this. I was using something in the trail compoment to delete the trail, and it was disabling the human gameobject, so I kept getting errors, I solved it later.
Just keep the script enabling/disabling the gameobject off the gameobject you're enabling disabling
Once a gameobject is disabled all it's components are also disabled
so no Update, LateUpdate, Awake, etc
but calling manually from other active scripts still works just fine
Yes, that's what I'm talking about.
If you connect this script to flashlight and disable flashlight, shouldn't that script not work?
Unity just won't call the methods that it normally would
But you can still call them externally from other scripts
But the friend wants to activate it again from the same script file.
That's why I told him to disable the light component instead of disabling flashlight.
Hey guys I wrote this very bad code thats very long. I think that I can make this shorter just by using a 2 dimensional list. Is that correct? If so, how would I go about making a 2d list. If someone could send a link to a guide or a good doc page, I would by thankful. Thanks!
yandere coding
yeah, thats why im trying to fix it
do you know A+1=B?
I'm not very good at coding but I think you could use a foreach or switch case to fix this.
so given an coordinate [A-Z][0-9], you can get wasd direction by adding vector2.up, right etc
Dictionary<string,string[]> myDict
add using
myDict.Add("A1", new string[] { "B1,"C1","D1" });
access using
string[] myCoords = myDict["A1"];
btw i will not represent coordinate in forms of string
string is inmutable and create lots of garbage, instead try
struct{
char row;
char column;
}
```total 4 bytes
what does struct{} do?
Same thing as a class but as a value type instead of a reference type. If you don't know what it is big chance you don't need it since this mostly falls under improving performance. I don't understand why it's being posted in a beginner channel to begin with.
public static bool IsCoordinatesTrue(string a, coordinate b)
{
return (b == a) ? true : false;
}
I've never used coordinates in unity, but you can use a function like this to check condition. Then write a function in the same way to change the coordinates. It has 4 parameters and changes down up left and right.
this got overwhelming
It seems like you could just use a 2d array here. I assume the coordinates represent a spot in a 2d grid?
is a 2d array like a 2d list?
So it's a matter of determing the x and y position
when i searched up 2d list I saw a lot of "arrays"
yes, spot in 2d grid
They are practically the same thing. I would advice you use an array unless your grid can grow bigger or smaller
yes
alr, Ill just look into arrays then
I think that it will be the easiest for me
I'd say see what an array is first
Then perhaps look up c# Lists, and then the difference between the two (spoiler: a List is a "resizeable" array)
If he doesn't know what an array is, I recommend he start a C# course first.
Judging by the question, they have already grasped the basics. It doesn't hurt to point somebody in the right direction, especially since they're keen on learnng.
No, just learning what arrays are won't help him much.
Shouldn't he learn other things too?
I suggest you advice them and not me
It will be much more useful if him learn at least loops, methods and structures.
Guys no need to argue
I'm already giving him advice, I'm just talking to you xD
thanks for the help
u re welcome
Honestly, sometimes the most mundane way is correct. However, something like a switch for cleaner code, or for larger amount of entries, a dictionary, would be ideal to grab the values you want.
Yeah, someone mentioned switched and dictionarys
Ill start learning about these
Never used them before
rn im looking into arrays tho
Dictionary a little more intermediate, so look into a switch first, also look into using else/else if
I know how else/else if works :)
Ah, ok just making sure your use case is correct since you're checking all values there
but thanks
regardless if you found the value you want
yes, you are right
you'd usually want your code to fall through once you find what you're looking for ;)
I suggest you look into both but practically it makes no sense to use a dictionary here
okaay..
These require a key and considering you're working with a 2d grid, nothing succeeds anything here
That's why I personally think you should use a 2d array, but see what suits you best
My god, if ur gonna do it like that, do use else keyword. 
looks exactly like my first tetris game I made in c++
Also the 2D array is the right answer here.
I suggest using it as a Vector2Int rather than just two ints and then just myArray[vector2Int.x, vector2int.y].
Hmmm, I should try out c++ sometime...
2D array works but then you have to also check for wrapping around the indices, actually that's only relevant if you use a 1D array as a 2D array. I forget, need coffee.
I think I won't, I'll try zig someday.

Also C.
Also assembly
Wait a sec, you don't need a collection or a chain condition for this.
This is literally just getting the coordinates to above, below, right and left.
that why i said 'A'+1=='B'
Hello guys, i just have this little part of code. But the hitpoint is always with Y = 0.5 i cant figure out why..
my plane ground is at 0, 0, 0
Hence the 2d array
Nothing in this question or image suggests anything that might be wrong
It's part of the learning process for them
this is my code xd
i dont modifiy the hit point, and it always do Y = 0.5
This a typical hitpoint
i remember plane has no height? or you use something that has "height" eg box collider?
the only thing i have on my moving player is a rigibody, and the plane has juste a mesh collider
My ground vs my spider
making a plane's collider Convex causes it to have height
look at the collider in the scene view
Not even necessary I think.
This looks like a 4x4 box.
Just get 5 Vector2Int and do this mathematically.
Then check if any of the structs have a value of X or Y value is 0 or 5 which is unused or just invalid.
Idk why he needs it in the form of LetterNumber coordinates string but hopefully, that's not even necessary or just convert it into that after.
oh
might have checked that box to test something, wait
thank you! i didnt know !!
Anyone?
that was just a prototype
I intended to change it anyways
show your inspector first
I have a strange issue where my player which is a cube cannot completely freeze it's transform.position.x so when I begin moving it lets say right and he freezes on the 3rd lane he starts jittering quickly left and right by a few decimals instead of remaining 0, I want the transform to stay at 0 after each freezemovement(). What's the problem? Here is the lane movement script I made: https://hatebin.com/lkvswnoqey I might have a conflicting movement left and movement right condition
I don't use RB much but usually you want to use its own methods to do stuff like freeze rotations or add constraints
something like that? I know you can freeze rotation on the rb in the inspector itself.
I think it's under the rotations tab to lock RB rotation to a certain axis.
There's also another field which has static in it, it might be a dropdown, which means it can't move at all.
how can i write this without getting the "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement" error.
because if I do allowjumping --; it says that the value cannot be null
a float
-=
what's the difference with -= and --?
I'm assuming u want to subtract allowJunping by 1.
yes
-- means subtract the variable by 1. -= means minus equals, you need to tell what you're the variable subtracting with.
both are little helping things that just condense a longer thing
myValue -= 1 just means myValue = myValue - 1
myValue-- just means myValue -= 1
thank god for IDE's 🙏
** and // should be a thing, it basically does nothing.
It's "valid" but it's the same as x = -y;
Seems legit.

Btw, I know basic math operations follow PEMDAS but where does modulo operator fall into?
just google "C# operator precedence"
Seems legit.
PEMDAS is just our own ruleset
you can always make your own and telll everyone else they are wrong
i put brackets around everything just incase
never trust anybody including yourself
they are tall and secure math walls and they are all i have left

thank you both @static cedar
Hi, I'm trying to make a sprite like the youtube video but when I click on chat bubble and try to make 2d object > sprite it shows more options than it does in the youtube video, any suggestions as to why?
because your editorversion is newer
exactly but whenever the game object touches the floor the float doesn't go to 0
like if layer mask/collision matrix doesn’t send a collision callback
this is trigger
Go through the physics messages troubleshooting resource in the pins
or if rigidbody isn’t configured properly
i dont think your ground is trigger that you can pass through so you need collision
it depends on how everything is configured.
it could be a trigger ground check hitbox, with solid ground collider
it’s hard to know without more info tbh
I don't get it sorry
i personally use oncollision so I can check normals etc, but I understand some people actually use a separate hitbox to look for ground
OnTriggerEnter only activates if you have a collider set to IsTrigger
OnCollision activates if both colliders are NOT set to IsTrigger
triggers are not solid, and never send force
https://gyazo.com/073b0f90f560f76920cd96df6843acd1
I've had this issue that sort have been on the back of my mind, Looking at other games in unity their bullet collision is perfect,
However, when my bullet hits the wall, the prefab for the explosion is a tad bit inside the wall. The prefab spawns in the middle of the bullet so technically it should be outside of the wall if the collision was perfect. The collision check is basically:
private void OnTriggerStay2D(Collider2D coll){
Instantiate(explosionPrefab,transform.position,transform.rotation);
Destroy(gameObject);
}
Things that i have tried.
- Set Bullet rigidbody to continous,interpolation and never sleep
- Reduced the physics time step to 0.01
I do not know what else i can do to improve it, any input is appreciated
you can’t walk on a trigger
yes you may have an additional hitbox to check, but in case no, use on collision enter (or attach a trigger collider hitbox on it)
the ground usually not a triggered collider
ah no wonder, because when I tried activating isTrigger to the floors, the player just fell through
anyway, the code is not the issue, depending on exactly how your collider is set up
your code is good IF you have a trigger collider under your player checking for ground
that method is kind of sus, tho, because it can lead to shitty ground detection on the edges
if both are solid, that code will not work
for ground detection, there are several methods, which you can find on youtube
compuational time less than overlap but you may get wrong result
I have 1000 objects and 1 prefab, I want to take the prefab and replace all the objects with this prefab
so that there is a blue prefab on stage
How can I do that?
you use code to instantiate the prefab on those objects’ spots, and destroy the other objects
yes, but I just get a gray clone, and I want this to be a prefab on the stage so that I can further override all these objects together
Casting the whole collider is most accurate imo, and also most expensive. The cost still is minimal, and very worth for physics that actually works consistently
I would probably make a component that allows a given object to replace itself
responsible for getting together the information of what to replace and all that
like position, scale, rotation for the new object. any parameters for the new object
then one singleton that has references to all hangars, and can tell them all to swap
or rather, a singleton that invokes an event, all hangars have that monobehaviour subscribe to that event, so when the event is triggered, they all swap
make sense?
Hello guys, interesting
I coded a scripts what has CrossFade functions
like CrossFade State_Changer/death and i have a rare bug
what if CrossFade State_Changer/death (one of this) started and then another... it's just buggy and like 1 in another....
or CrossFade death started but he doesn't change his animations....
I have already made the replacement,I need to figure out how to make this object so that this object is a PREFAB WITH THE POSSIBILITY OF OVERRIDE BLUE on the scene
Okay, I did it with the 2d array
it works
and its better then what I had before
so Ill leave it like this
Why does my IDE say the else is redundant when I uncomment the commented return line?
because you can just do:
if (stuff) {
things;
return data;
}
container[whateverblabla]
return data;```
since there's a return in the if, the else is not necessary since control will not continue after the return
it's basically an implied else
also you can do this:
if (stuff) {
// things
}
else {
containterblaiblah
}
return data;```
Instead of having two returns
since you're returning data no matter what
Close enough, good job
I have this dashing code on my PlayerMovement script.
And I'm calling it from my PlayerInput script just like that
But when I dash player sometimes goes 3.2 and sometimes 4.8 units
Weird... How can I fix it?
I can't say it's framerate dependent because there is only 2 numbers as I said
Btw, is there a reason that u need it in A3.. those stuff? 
It's possibly a framerate dependency issue and possibly related to your calculation for the velocity
- You are using WaitForSeconds which is not going to wait a constant number of physics updates
- where does the
directionvariable come from?
anyone know how to delay a function from happening?
Call it after the delay..?
how do i make a delay
Use a coroutine
A timer in update, a coroutine, async await, etc...
I'm setting the input vector2 here on PlayerInput script
"How do I make a coroutine"
Use code
"How do I code"
it is the invoke thing right
No
Are you using a joystick?
Keyboard
Is it intentional that direction will NOT be reset/set to 0 when you release the keys?
Yes to make the player be able to dash when not moving
also where does dashSpeed come from?
It's a float
If that's never changing then it goes back to my first suggestion:
You are using WaitForSeconds which is not going to wait a constant number of physics updates
Is this a suggestion? :D
It's a suggestion of the source of the error.
So what should I do?
if you want to wait a constant number of physics updates you should do this:
int numberOfPhysicsFrames = Mathf.CeilToInt(dashDuration / Time.fixedDeltaTime);
for (int i = 0; i < numberOfPhysicsFrames; i++) yield return new WaitForFixedUpdate();```
^replace the WaitForSeconds with this
you can do CeilToInt or FloorToInt, depending on if you want 0.05 to become 0.06 or 0.04 (since your fixed timestep is probably 0.02)
I saw literally 3 tutorials doing the same code for Dashing.
Your code is working!
Bro
The way you approach the problem..
*professional ✨ *
Would anybody know how when reactivating a gameobject (gameobject.setactive(true) to be at the same location as the player? Because when the game object is unactive, it's position is locked
So this code is getting the number of Physics frames during the dashDuration time. And Calling the WaitForFixedUpdate() function numberOfPhysicsFrames time
Am I right? @wintry quarry
Unity physics happens on a fixed timestep basis, so yes we're calculating "how many fixed timesteps does our dash duration require?". Once we know how many it requires we wait exactly that many fixed updates which means that many physics simulation steps will occur.
This ensures that the velocity you assigned to your body is applied for the same exact amount of physics simulation time every time.
so im working on a game that is based on laser and reflections and all
and i am trying to detect collision for one of my objects tagged "flower"
heres the detection code : public class CollisionDetection : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Flower"))
{
Debug.Log("Laser hit a flower!");
}
}
its pretty simple and i think its correct
but it doesnt detect it no matter what i do
any tips?
Thank you so much!
Do both objects have 3d colliders?
Does one of the colliders have "is trigger" checked?
Does one of the objects have a Rigidbody?
Is the script attached to one of the objects involved in the collision?
Does the other object have the appropriate tag?
When a game object is unactive, are it's variables static? For example can you still move it when it's unactive?
yes
no
no i dont want them to have physics
no its not its attached to a laser pointer
yes
- At least one rigidbody is required for OnTriggerEnter
- At least one collider with Is Trigger enaqbled is required for OnTriggerEnter
you will need to add those things for this code to work
(you can use a kinematic rigidbody btw)
no its not its attached to a laser pointer
Also OnTriggerEnter only works when attached to one of the two objects in the collision
Since this is a "laser" puzzle or something why are you trying to use OnTriggerEnter?
Wouldn't a raycast be more appropriate?
i do have that in the laserbeam script so it would reflect by hitting a mirror tagged object
right so why are you trying to use OnTriggerEnter here?
It doesn't seem like you have anything remotely close to the setup required for OnTriggerEnter
this is the scene i have and the black object is the flower tagged one
it doesnt print anything in the console
of course it doesn't print anything
as I explained you don't have anything close to what is required for OnTriggerEnter to work
I also don't see any black objects
i tried to use OnCollisionEnter but it didnt work either
grey*
OnCollisionEnter is ALSO very inappropriate for what you're trying to do
you should be using raycasts
so how should i modify the collision detector script?
throw it in the trash
and?
make a script that shoots a raycast and interacts with any objects the raycast hits
as i said i have laserbeam script which uses ray cast i dont know if its related or not
public class LaserBeam
{
Vector3 pos, dir;
GameObject laserObj;
LineRenderer laser;
List<Vector2> laserIndices = new List<Vector2>();
public LaserBeam(Vector2 pos, Vector2 dir, Material material)
{
this.laser = new LineRenderer();
this.laserObj = new GameObject();
this.laserObj.name = "Laser Beam";
this.pos = pos;
this.dir = dir;
this.laser = this.laserObj.AddComponent(typeof(LineRenderer)) as LineRenderer;
this.laser.startWidth = 0.1f;
this.laser.endWidth = 0.1f;
this.laser.material = material;
this.laser.startColor = Color.white;
this.laser.endColor = Color.yellow;
CastRay(pos, dir, laser);
}
void CastRay(Vector2 pos, Vector2 dir, LineRenderer laser)
{
laserIndices.Add(pos);
Ray ray = new Ray(pos, dir);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 30, 1))
{
CheckHit(hit , dir , laser);
}
else
{
laserIndices.Add(ray.GetPoint(30));
UpdateLaser();
}
}
void UpdateLaser()
{
int count = 0;
laser.positionCount = laserIndices.Count;
foreach (Vector2 idx in laserIndices)
{
laser.SetPosition(count, idx);
count++;
}
}
void CheckHit(RaycastHit hitInfo, Vector2 direction, LineRenderer laser)
{
if (hitInfo.collider.gameObject.tag == "Mirror")
{
Vector3 pos = hitInfo.point;
Vector3 dir = Vector2.Reflect(direction, hitInfo.normal);
CastRay(pos, dir, laser);
}
else
{
laserIndices.Add(hitInfo.point);
UpdateLaser();
}
}
}
do you think i should use if (hitInfo.collider.gameObject.tag == "Flower" or something like that?
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
yes in this script you need to check which object you're hitting. You can check for tags or components or whatver you want.
yeah i didnt knew sorry
Notice how you're already doing this to check for mirrors:
if (hitInfo.collider.gameObject.tag == "Mirror")
the flower would just be a different case
When a game object is unactive, are it's variables static? For example can you still move it when it's unactive?
no variables are not "static" in that sense ever
That's not what "static" means
oh your right forgot that
thanks for the help
And yes "static" has a specific meaning in C# that has nothing to do with whether they can be changed or not
static variables are not "variables that don't change", they're variables that belong to a class instead of an instance. You're thinking of "readonly", and no, variables don't become readonly when an object is disabled
so for example if I said that the unactive game object to have the same position as the player, if i reactivated it would it be at the position it was unactive or at the player's position?
it would be at whatever position it was set to most recently. The active state of the object is irrelevant.
I'm attempting to write a function that'll print a tuple of unknown length and content types, but I don't know how to specify that with syntax
tuple.ToString() doesn't work?
no way
Yeah that's what I was getting before
I want to see the individual values in the tuple
well actually this is not a tuple odf unknown length
Can't you foreach over it
this is a Tuple of length 1 explicitly
Oh yeah Tuple<T> would be a single entry does that even work
How do i specify unknown length then?
ITuple
Which btw has these properties:
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.ituple.length?view=net-7.0#system-runtime-compilerservices-ituple-length
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.ituple.item?view=net-7.0#system-runtime-compilerservices-ituple-item(system-int32)
Alright I'll look into that
Thanks
So I've written my function but now I can't pass my (int, int) tuple into an ITuple param
Not seeing information on the difference between the two or if I can convert a tuple to ituple
Wait, one sec
Ahh nevermind I just wasnt reading the error properly
yeah you've got an array there
the tuple itself should fit fine
I recommend using a StringBuilder rather than string concatenation btw. The performance will be much better
Yup, works now, I was just being blind lol
Thanks for the tip, I know about stringbuilders but since i'll really only be using the print function for debugging im not too concerned about performance
maybe i should do it anyway tho
eh not a big deal
Type mismatch when trying to add a projectile spawn point to a scriptable object
Pretty sure editor will show "Type mismatch" for a scriptable object initialized during runtime
Think that applies to gameobjects as well but not sure
@hollow zephyr are you trying to add a scene object into a Prefab or SO ?
An SO
yea u can't do that
oh i see
Is there a pattern that I should be using to accomplish what I am trying to accomplish?
have the spawn point on the same script that uses the SO for data
The issue would be that not every spell has a spawn point
GameObject tracer = Instantiate(_trail, barrel, transform.rotation);
Rigidbody2D rigidbody = tracer.GetComponent<Rigidbody2D>();
rigidbody.AddRelativeForce(tracer.transform.forward * _bulletspeed);
anyone one have any ideas why this wont move the gameobject it just stays still when it gets Instantiated the bulletspeed is 10
transform.forward is along the Z axis (assuming a normal object orientation in 2D)
in 2D that doesn't exist
so basically you're doing AddRelativeForce(new Vector2(0, 0))
maybe that can be a bool or something ? I'd have to know a bit more about your setup
try transform.right or transform.up
Hmmmm, would it be a good idea to somehow get the spawn point from the parent that I am passing into the Activate() function?
The parent in this case would be the player, and the ProjectilePoint is a child of the Player, so maybe using parent.GetChild() or something like that might work?
What would you need to know from the setup? Im happy to give details
can anyone help?
https://hastebin.com/share/diqocarese.csharp
I getting an a error on
if (EnemyUnit.unit_type == 1 && ground = true)
and idk why
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I getting an a error on
What error?
The left-hand side of an assignment must be a variable, property or indexer
Why are you doing ground = true?
that sets ground to true
use == for comparison
when do you call Activate, sure you can pass it thru that
or directly reference the transform
your code is doing (some bool&&some bool)=some bool, but the result of && operator is unassignable, so the compiler give you this error
Hi! sorry I am a beginner and I am studying video game art and design in college. We've been using the unity playground asset set for some prototyping just to get used to unity and stuff. Thing is I am brand new to C# and have 0 experience. I would like some help with a script
#854851968446365696 guidelines how to ask for help here
omg I'm too adhd that's all overwhelming.
I'll just copy the format people above use for asking for help
Hey, how do I fill a 2 dimensional array with game objects?
a normal array works normaly, I see it in my inspector and I can fill it up
but my 2 dimensional one doesnt even show up
yeah unity doesnt serialize multi dementional/2d array
Hmmm, so how do I fill it up then?
Put an array into a struct and make an array of the struct
omg
also you would use a gameobject to nest into to create a "group"
Everything in the hierarchy has a parent. If you put something inside of another object as a child of it, it will be attached to it.
Then you can collapse the parent object
I guess I'll just go the long way and create an empty game object and but everything inside my little group as a child
What would you expect to be the "short way"
how else would you group things
I mean on 3D modeling software you can use ctrl+G and it just groups things together and makes a folder. was just assuming unity had same functionality
Select multiple objects, right click, create empty parent
Isn't an empty gameobject basically a folder
You can move a bunch of objects into a new parent by multiselecting them and creating an empty from the right click menu
yes hierarchy has no concepts of folders, they're all gameobjects
Yeah
thank you
I suppose you could get a package to make "header" folder but it's still a gameobject
what exactly do structs do?
better than nothing tho
I dont really understand them
they're like a class, but they're value types
I am trying to get the point on the mesh but when it tries to get the point of the mesh on a different one that is not the middle one it then says nope
Anyone know how to fix this?
google structs, also as navarone said
@candid oyster also you'd have to add [Serializable] above it to see it in the inspector
above the struct yes?
yes
how can i make a background that is infinite so where ever the camera goes the background is still there
alright, thanks
just move the background with the camera
Or just use a skybox
^
still same thing
something like this should work
public class Awesome : MonoBehaviour
{
public GameObjectArray[] GameObjects;
}
[Serializable]
public struct GameObjectArray
{
public GameObject[] objects;
}```
thanks, this will help
move the main anchor, and move the background attached to it separately
I am trying to get the point on the mesh but when it tries to get the point of the mesh on a different one that is not the middle one it then says nope
Anyone know how to fix this?
Have an empty GO with the background attached to it, move the empty one alongside the camera and do whatever you want with the background itself
Dont I need to put a comma in between the []
?
or just spawn/despawn backgrounds as you move
I thought that thats how to make it 2 dimensional
no because that defeats the whole point of doing this
oh
okay Ill try to mess around with it for a bit too hopefully understand it
i tried to do that but i dont know how
have a grid-like background system and track the camera position
spawn backgrounds in the camera range and despawn when they get out of range
ok but when i spawn a back ground how do i know where to put it next to another background pieace
stupid question. Is the struct supposed to be in a different script? I never messed around with classes
the struct can be either in the same script or separate file
just declare it outside the Mono class
its giving me an error that it doesnt understand the [serialized]
you need to add using System;
at top
or is it fine to have a lot of background that all have their sprite renderer disabled and when you move to it it gets enabled
in c# you have two ways to create 2d (or multi dimensional) array: [,] and [][] (list of lists is just a wrapper of second one), unity wont serialize first one but with some trick it can serialize second one
otherwise if you really wanted to create a [,] and see it inside the inspector , you'd have to make a custom inspector/property drawer
show whole error
Look at the actual error
you expand the console and look more details
not just the first line
try restart editor
how can i make a background the is infinte so where every the camera is the background is there
Skybox
ok i will try that
Hey! actual coding question this time.
// The key to press to create the objects/projectiles
private KeyCode keyToPress = KeyCode.Space;
how do I make it so instead of a key being pressed, it's just constantly shooting.
private ?? ?? = true;
You'd have to look at where the shooting actually happens
it is just a variable, nothing to do to make you continously shooting
instead of where you define which key does it
so how exactly is this array 2 dimensional?
also !code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
It's an array of an object that contains an array
it is basically an array of arrays
oh so maybe I can make a variable bool which I can bind to where it actually shoots
Which is not technically 2D, but close enough that can still be serialized
ohh
doesnt look like your ide is configured either.
so lets say I want to have a 4x4 2d array
so it basicly makes 4, arrays each habing 4 slots
You would have an array that contains 4 of this object that each have an array of length 4
I literally started coding yesterday 😭 plz
all good, but you you dont want to be coding without a working ide
If you just started coding just stick to easy stuff for a while.
!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)
Idk what ide even isss
so how do I fill it up with my game objects? in my inspector I just see it like a normal array
You add the arrays to it through code in a loop. Or at least that's how I do it.
You should be able to expand the inner element and add your objects to it
wait a moment...
Technically you can make a 2D array out of a single array but it's a bit more mathy
using the 2D array data structure makes it a bit easier though
now its working, thanks
yes, I did that but it doesnt show up in the inspector then
Yeah, unity doesnt like those
Im having an issue with trail renderers and sorting layers
so i have my gameobject over the top of a tilemap which the sprite its self is visable but the trail renderer isnt visiable while over the tilemap
they are both on default layer and the trail renderer is a layer above the tilemap but still not visable
No you can't. It'll just be one big array. You'd have to code in a way to separate them right?
there is no multi dimensional array in computer memory
not a good idea
you can have as many dimensions as possible in a 1D array, but it's up to you to handle the navigation of it all.
but yeah in memory it's just a straight line down ;)
@timber tide Yeah but then why use bools when you could just use ints? Why use anything that makes it easier?
hi, little question how i can show and hide my canva in code????
setactive
same reason people use C still
k i gonna look that tysm
canvas.enabled = false / true
i need import the canva before or something like this?
you'd beed a reference to it regardless
if type is Canvas you use .enabled
if you use GameObject type, then use SetActive
oh ok its a canvas for me
Multidimensional arrays are stored in memory as single-dimensional arrays anyway
just [SerializedField] private Canvas canvas
and drg the component inside
You can do math to get the 1D index given the X,Y coordinates
i need make someting like that ?
Canvas canvas = canvas.GetComponent<Canvas>();
canvas.enabled = !canvas.enabled;
canvas.enabled = true;```
no
but how would i know where to respawn the background
If you already have a variable canvas, why GetComponent from it
Just use the variable you already have
idk its just a random thing i find in google xd
how do I access the arrays now?
For example before in my 2d array I just did:
Array[Value1,Value2];
based on the camera position -> transform the cam pos into grid coords and spawn background in range of these coords