#💻┃code-beginner
1 messages · Page 97 of 1
public ObjectType objectType { get; private set; } = ObjectType.Stone;
If you want a default
It should default to stone already though. I think default is 0
ah so that just makes it appear as a dropdown, which can change
sorry for the inconvienience
You may need to do a [field: SerializeField] attribute above it.
Unless you mean you already see the dropdown?
No inconvenience at all 😄
Hello, I'm trying to make a movement system in the style of the collide and slide algorithm but the walls kill all velocity and the ramps make you much faster, is there anything obviously wrong with my code?
This is the script:
https://hastebin.com/share/agoqurucad.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
change the materials you are using
something like this idk
then they won't get stuck
It's not a rigidbody
why is Coroutine is so buggy when placed in FixedUpdate, I created extra animations for the slime to leap toward the player but when I try to execute it in Coroutine, it is just terrible. The amount he dashes is usually half the Distance i set, or maybe even one tenth, or zero. I use virtually the same code in fixedupdate with SlimeDash a new State, it works just fine
Still can't get curly braces to auto format on the same line on the new unity vs code extention with c# dev kit
You usually dont want to be calling a coroutine from Update/FixedUpdate/LateUpdate, since those run per-frame, that would be calling a new coroutine very often, which can lead to very strange results, if you are going to use a coroutine, you want to make sure you are only calling one instance of it once
Occasionally. It depends on if the user asks the question
Ah ok, thank you
tried editorconfig, doesnt do anything with the new line thingy
I'm using the class reference method but the variable value is not being retained between classes
{
PathContext pathContext = new PathContext();
while (pathContext.TotalTimeElapsed < chaseDuration)
{
yield return _pathfinder.MoveAlongPoints(pathContext, _pathfinder.GetPoints(target.position), RecalculateSpeed, _moveSpeed);
Debug.Log(pathContext.TotalTimeElapsed);
}
}```
I'm modifying its value on the pathfinder class but when it returns the value is the same
Are you talking about TotalTimeElapsed?
yea heres the coroutine on the other class sorry for the length ill edit it
Use a pastebin site if it's too long.
{
int pointIndex = 0;
while (pathContext.PathTimeElapsed < duration)
{
Vector3 targetVelocity = Vector3.zero;
if (pointIndex >= points.Length)
{
targetVelocity = Vector3.zero;
}
else if (Vector3.Distance(transform.position, points[pointIndex]) > .1f)
{
targetVelocity = points[pointIndex] - transform.position;
}
else
{
pointIndex++;
}
Move(targetVelocity, moveSpeed * Time.deltaTime);
pathContext.PathTimeElapsed += Time.deltaTime;
pathContext.TotalTimeElapsed += Time.deltaTime;
yield return null;
}
yield return null;
}````
But generally, it seems like you're creating a new class instance in the coroutine, so it obviously is not modified by anything anywhere.
Hmm
Debug.Log is returning the same value 0.1012646
which is the duration inside movealongpoints so it makes sense
its not retaining the modified value in the class called
I feel like there's some confusion with the coroutine yields.
No. With yield return AnotherCoroutine.
is there an alternative? this is the only way i know how to run another coroutine within one
For starters debug what's going on. Use the debugger to step through the code or add more logs.
ok
What is PathContext? You should show that code.
I kinda feel like the nested coroutine just only does one loop before finishing.
a simple class
{
public float TotalTimeElapsed;
public float PathTimeElapsed;
}```
I just tried declaring the time elapsed value on the second coroutine, whats happening is the value of TotalTimeElapsed is not being saved when being modified in the other coroutine
i finished the brackeys tutorial and its good but glimpses over the coding too fast, whats a better series to follow with a lot of focus on coding?
Unity Tutorials are nice they have guides on their officail youtube
Declaring a new variable in the second coroutine, obviously wouldn't help at all. The code you shared is correct in terms of sharing the value between coroutines. You just need to debug what's going on.
I found it it was this ``` pathContext.PathTimeElapsed = 0;
while (pathContext.PathTimeElapsed < pathDuration)```
I had to reset this variable every time it entered the second coroutine
in my game i have a grappling hook and right now im using a lienrenderer to draw the line between the player and the end of the grappling hook but i want to make the line look like a rope and not just a renderer line. so i made a rope sprite but how should i go about making a rope sprite that can dynamically change sizes depending on the distance between the player and the grapple end and that conencts the 2.
why is he multiplying the mouse movement and not just adding it to the rotation, can someone explain the logic?
you arent supposed to multiply mouse input by Time.deltaTime, this tutorial is bad
can u tell me a better tutorial
im not sure what you're doing, plus i rarely look at tutorials myself, so i cant
i watched another tutorial and it also u ses time.deltatime
what should it be instead
i believe you can just exclude the Time.deltaTime, most tutorials do this because one guy did it and every tutorial is a copy paste of each other. Most people who make beginner tutorials arent very good themselves.
As for your question about "not just adding it to the rotation" im not sure what you mean, .Rotate will rotate the object
I was looking that up too and I see a lot of tutorials multiplying by deltatime
but I swear I've had it working without it
oh right doesn't a brackys video do that
i think thats where it came from, i wonder where he got it from lol
Ah, ok GetAxisRaw is frame independent, but you have to do your own lerping if you want to smooth it, but GetAxis seems to already do most of that work for you.
If I'm understanding correctly
So I guess it's just people getting mixed up between the two
Mouse.current.delta.ReadValue(); would be considered the raw values too
Scaling by deltaTime doesn't smooth something that is already frame-rate independent anyway, it just ruins it
you would need to actually perform some sort of filter to smooth
how do i call a function from another script?
guys, I have a question!
do I need to normalize the input of vector2s of the input package??
Not necessary, that should already have a magnitude of 1. You can Debug.Log it to confirm.
understood sir!
is invoke deprecated?
no
how can i fix this? Find is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'KeyClicks' on game object 'KeyHandler'.
what do you not understand about that message?
you need to understand the message and do what it tells you to do
it says to call it in start
no it does not
ok, what line of code is producing the error?
no
!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
what is then?
it doesn't say what line is making the problem but it started after i made that line
screenshot the console with the message selected
literally just downloaded unity randomly doing things
trying to make the camera rotate around the x axis of the player. Keeps spinnin on y axis when i hold down right arrow.
well im sure this will look bizzare but im just piecing anything together
the complete console window
do you have domain reload turned off?
what does that mean?
do your scripts recompile automatically when you change them?
facing this exeption when create build
close your project and re-open it
Post the entire error message to #📱┃mobile
okay i have done that know and no errors so far
only this
so what is KeyClick.cs line 14?
so audioHandler is null
yes
i think i fixed it though
i got it working, thank you so much @languid spire you made my day
Rotating on the x axis would mean your camera would be looking up or down. Your current code doesnt make a lot of sense, you should just follow a tutorial/use cinemachine.
Item equippedItem = equipmentSlot2.GetComponentInChildren<Item>();
does this always throw an error if there is no Item?
should I use var instead?
var just means that the compiler guesses the type from context; the end result is exactly the same
no, that will only throw an exception if there is no equipmentSlot2
anything very wrong im doing here?
yes, but as mentioned you might be better off following a more complete introduction to camera control and rotations rather than getting someone to correct random stabs in the dark 👍
In my game enemy attacks if float attackRandom > attackProbability. I want to increase the chance of attack steadily on runtime. But Im not sure how to keep incapsulation here. I dont think making attackProbabillity public is a good idea. Score is saved in GameManager and attackProbability is stored in enemy script. How do i keep attackProbabillity private?
So, depending on the score, attack probabillity should be increased
You can consider reading from GameManager's score from where attackProbability is calculating
So, making score public?
You can always read publicly if you want to do that, and set as private
Attack method is realized throught InvokeRepeating and i thought maybe i should += to attackProb some multiplier that is calculated based on score until probabillity reaces 0.6
aaaah, right
public get, private set
thanks!
Yeah, there's a bit more to it when it comes to reading references publicly, but if it's some sort of value type then it's as easy as that.
you should probably change your architecture
what if you will have 10 equipmentSlots
equipmentSlot1 equipmentSlot2 equipmentSlot3 ...
pretty cool how you can deduce my architecture from one line of code
just trying to advice ;p
the 2 is just because I'm checking if I need to unequip the item in the right hand slot when equipping a 2 handed weapon
KeyBindType.text = objectData.keyBind; I'm trying to convert a KeyCode into a string, any idea how to do that?
.ToString()
Hi guys, how are you ?
I'm trying to add an onclickFunction on a Instantiated button. I know the add listener system, but since my button is not instantiate at the beginning of the game, i dont know how to do that :/
Why would it matter when it's instantiated?
is it a prefab?
because i got a script that create row like this, each button must have the same function (the one i'm trying to implemant), but with differents arguments
I still don't see how that prevents you from adding the listener
can't you just add the script to the prefab and assign the function in the prefab?
i dont know why, ive been scripting in another engine for more than a year but when im using unity it feels like im starting from square one again. I feel so clueless despite my experience in another engine.
maybe i dont understand something with listener then x)
nop, the argument is a dinamycally path
So you ask how to post code in another channel and then post it incorrectly here. Why?
Maybe if you explained how you would add the listener if the buttons are instantiated at the beginning of the game, and then explained why you can't do the same thing if they're instantiated later, and someone could point out where the issue is
ObjectData objectData = interacted.GetComponent<ObjectData>();
KeyBindType.text = objectData.keyBind.ToString();``` wouldn't this get the script component from the raycasted object, and then take the KeyBind variable and put it into the string?
I debuged it and am getting the error right after:
Which one is line 30?
debug it all
keep in mind the Debugger can be good for some of these things. Debug mode lets you peak into the contents of all variables up to your breakpoint.
Why I am getting null refernce when i call mergelist function?
Where I convert the key code to a string
The third line of the code I put in
so either KeyBindType, objectData and/or keyBind is null. Debug them
post full error and code with line numbers
did I say text?
No you didn't
You're not referencing the method there also looks like you got a hanging bracket. Do you have your ide connected to unity?
Mb
Hi!
I know I'm having amoment where I'm being very dumb, but my brain cannot currently figure this out. Why can't the GameManager see exitpermitted() ?
I'm doing a Uni assignmkent, but the professor isn't available due to ahving covid.
what's the error
exitpermitted doesnt exist in current context
it's in a different class, of course you cannot see it\
And is there a function called exitpermitted in that script?
exitpermitted() is in the ExitPossibleIndicator class within a script document of the same name. I thought I'd be able to reference it in the GameManager since it's all set to public.
you need to learn some c# basics
You have to call that function on an instance of ExitPossibleIndicator
You have to tell it which of those you want to call the exitpermitted function on
I am currently working on a boss and i have 3 attacks for it, spray which works fine, bulletwall, which works occasionally but sometimes doesn't register as completed, and smash which doesn't work at all. I've been having trouble with this for a while now and I can't seem to figure out the problem. this is the script attached to the Object: https://gdl.space/xiyezuroye.cpp
you might want to look into StateMachine behaviour
would fit percetly in there instead of doing everyhing in one big function in Update()
what if you will have 10 attacks, you will need to make 10 if/else statements and a huge code wall
Thank you, and sorry for doubt you but I wanted to make sure you had all of the information.
This is exactly what the professor wants. I am stuck on the very end, trying to call the thing from another script. I want to make sure this still applies. We've only been coding in Unity for 4 weeks, a couple of hours every Monday so I'm not used to this yet.
https://unity.huh.how/references
You have to call that function on an instance of ExitPossibleIndicator
You have to tell it which of those you want to call the exitpermitted function on
I will look into that but I am not planning any more at this time since I'm on a deadline.
BulletWall();
AttackFinished = false;
wrong way round
best to always put AttackFinished = false; first
that seems to have fixed the problem with that attack.
but the smash attack still doesn't work at all
I'm making a simple class (Bounds2) which is basically Bounds but for 2D.
I want separate constructors to make by min and max, and another to specify by center and size. But both would have the same arguments. Is there a way to do this with constructors? or is the cleanest way just to make a static method that makes a new Bounds2
hi! is there an attribute that can make a header collapsible?
Hi is netcode the best option for multiplayer in unity?
The most basic way is to just throw it into an innerclass
otherwise there's stuff like naughtyattributes (could be a unity attribute but I forget)
It's the best option for local, or more client authoritative focused multiplayer games
at least in my opinion there
this is pretty cool, thanks!
i made a package that adds some editor attributes to unity, one of them is the Foldout attribute which looks like this, if you want i can send you the github link
What is this for??
@icy grotto how u made model's AI???
exactly what I need. yes please send link, thank you!
ima DM it to you cuz idk if im allowed to send it here
How do I make my app's UI work with all screen sizes? I've got my Canvas on Scale with screen size but my text boxes will look great on one device and then when I switch to an iPad Mini 4 or something like that, the text boxes are off the screen. My UI is currently a couple of input fields that I'm using for testing i.e. there is nothing fancy
just make sure you anchor things properly
Of course 🤦
@undone rampart how do you think I could implement code that checks for overlapping text boxes and reduces the size so they fit correctly? That will be an issue too
that sounds like something layout groups would solve
Great, I'll check that out. Thank you.
Edited a script while in play mode accidentally. How can I fix?
The referenced script (Unknown) on this Behaviour is missing!
Remove it and re add it
those are kinda tricky to find sometimes
There are no references in the scene, the script that was edited is instantiated by another script
may have edited a prefab
Check the prefab
Pretty sure I don't have a prefab
What are you instantiating then?
Just using new() MyScript
That has nothing to do with the error then
The error is talking about a broken MonoBehaviour reference
You wouldn't be using new for a MonoBehaviour
If you are that's a problem in and of itself
Yeah that's what I was confused about
The only script that I edited during play mode
Was a script that does NOT inherit from MonoBehaviour
So I don't understand how there's a broken reference there
But I restarted Unity and all is well so I'm not sure...
you can't really make changes in the code during playmode
that can lead to many random errors
Yeah I know, just thought I had stopped the game, but I guess not
- dont modify scripts during playmode (even at paused)
- dont refresh the project during playmode
- dont make new scripts, dont delete any scripts, don't do anything that requries re-compiling the scripts
Hey guys, is there a way to reset the Time.time? I am trying but it is not allowing me saying its just readable. And I am having a problem where if you die in the game, you go to the main screen again, and when you press play, the Time.time is not ZERO again, its the same as before and that is messing with stuff..
This is a TMP_Dropdown object. How can I increase the size of the option backgrounds?
You'll have to make your own timer
oh ok, sad.. thank you!
Use Time.timeSinceLevelLoad or better yet just your own timer
Or a code question but just modify the template object
yeah I created a new script just to control that.. boring that unit doesnt have a way to reset its own timer..
Thanks. In the future, where should I ask this? Couldn't find a channel that really fit the description, unless this is counted as #🖱️┃input-system?
Time.time is the number of seconds since the application began running. You can use it for differences, but should not use it for absolute values
Closing the game and starting it will reset that value
Resetting it artificially would defeat the purpose of it
Ahh thanks, I hadn't bothered to check artist tools
Hello! please help me in creating a code, I have no idea on how I can display data in a unity scene from firebase, I know how to get data from unity to firebase but I don't know how I can display it on my unity scene. For ex. the age of player, I know how to get it using api to firebase, but how can I display to my unity scene in terms of "Text"?
please provide example code
You can create a text game object in the scene (either Legacy Text or TMP Text) and then within a script, serialize that text object
myTextComponent.text = "words"
I dunno firebase though, sorry
Could use string interpolation to make it simple too
myTextComponent.text = $"Player Age: {playerAgeVariable}"
let's say
[SerializeField] Text textBox;
Then use your API, let's say this:
string APItext = GetAPIText();
textBox.text = APItext;
And boom
Thank you so much to the both of you! I'll try them! 😊
you almost definitely want TMP_Text not Text
Okay! so something like this
[SerializeField] TMP_Text textBox;
Hello!! I am working on FPS mouse and player movement scripts. They both work and I can move / look around in game mode. But when I start game mode my camera is facing straight down to the ground… is there something I am missing in camera settings or is this a script issue?
how do i increase and decrease the y value of a game object by a set amount?
transform.position += new Vector3(0, 5, 0);
no
Yeah, that is wrong sorry
Add a new vector3 with the y component as 5
Can't add to the y property directly
How would I check collision in a class?
I made a class that creates projectile, but how would I check if it is colliding with something? (I want to do the collision check in the same script, because projectiles can collide into others projectiles)
thanks
ok so hold up
Edited
OnCollisionEnter
I can not use monobehaviour function though?
Oh, ok. I didn't see you mention that requirement
That is not how you should approach it. A projectile should check for the collision and then maybe call a method on the spawner, but having the spawner do the checking is nonsense.
how we supposed to know that without seeing at least scripts 
Oh dang, I misread that bad. It's the SPAWNER you want doing the checking? Why?
I actually didnt expressed myself correctly, I do want to check collisions IN the projectile class, not in the original class (spawner)
Sorry!
And why can you not use a MonoBehaviour method like OnCollisionEnter?
I dont know how to do it..
It doesnt let me
📃 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.
Yeah that's how you'd normally do it
My script looks something like this: (I'm on phone sorry)
public class Projectile
//Info bla bla
But then I can not do OnTriggerEnter
Why can you not
so just make projecticle monobehavior whats the big deal..
I would take a look at the documentation link I sent
It gives me an error wait let me bootup my computer
See how it is done correctly
Alright so that's my class (i don't need to s end everything)
public class Projecticle : MonoBehaviour
{
GameObject projectileBullet;
public Vector3 projectileSize;
public Vector3 projectilePosition;
public Sprite projectileSprite;
public string projectileName;
public float projectileSpeed;
public Rigidbody2D projectileRigid;
}
and when I do that, this happens
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
UnityEngine.MonoBehaviour:.ctor ()
PlayerHandle/Projecticle:.ctor ()
PlayerHandle:Shoot () (at Assets/Scripts/PlayerHandle.cs:135)
PlayerHandle:Update () (at Assets/Scripts/PlayerHandle.cs:145)
Why are you trying to create a MonoBehaviour with new
I'm not?
Ok, that error has absolutely nothing to do with OnCollisionEnter btw
I'm just instancing a object
Projecticle newProjectile = new Projecticle();
that's not how you do it?
That is literally creating a MonoBehaviour with new
what did you think that meant
If you want to instantiate something, you should, y'know, use instantiate
Instiantiate works on class too? I didn't know thanks!
It doesn't let me do this though
Projecticle newProjectile = Instantiate<Projecticle>();
no its for classes that inherit Object
Right
MB is a special class
https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
Oooh okay
I get it
Because that's not how instantiate works
you pass it an object to clone
Projectile is a MonoBehaviour
// examples
// to add to an object
Projectile projectile = gameObject.AddComponent<Projectile>();
// to instance from an existing projectile, which clones the whole object it is on
Projectile projectile = Instantiate(existingProjectile);
Such as a prefab
Projectile projectile = gameObject.AddComponent<Projectile>();
thanks, that's what i needed
Instantiate requires a parameter
This adds a projectile component to THIS object
This will add the projectile component to the current object
that's probably not what you needed
use more reliable Ground Check
the one built into CC sucks ass
it only check when moving as you said
Yeah I won't add it to the current object
You should only call .Move once per frame. Combine the calls into one that has both horizontal and vertical movement on it
It would be:
Projectile projectile = Instantiate(projectilePrefab);```
It's fine as long as you actually make sure to have a small amount of gravity at all times, even when grounded
and that you don't make The Brackeys Error of calling Move twice
true its not horrible, but still doesn't provide a decent slack like Overlap or Cast would
but def combine Move into.1 call
The projectile isn't a prefab, i'm actually making a projectile from a class.. It doesn't exist before invoking the class
If you need that much precision you should be using a rigidbody-based controller anyway
Then make a prefab
oh that explains it
what's a better way
as like a model? and then I adjust the stats in the class instead of actually making the projectile in the class?
You should make a prefab that is your whole projectile
and spawn that when you want one
Make an object in the scene, add your Projectile component to it, set it up, drag into the project panel to make a prefab, drag that prefab into where you need to clone it from, Instantiate that prefab now.
I just follow the Unity TPC/FPS premade controllers
They uses overlap which fixes a lot of inaccuracies (cc on slopes says it not grounded sometimes when going fast)
Thanks!
i was originally but changed it
i'm probably gonna change it back
cause i prefer it
its Class -> Object right?
Yeah i get what you guys wanted me to do !
I'm just really used to SFML, where I code everything in one script
I didnt think about making another script lol
An object is the child of a class
ye
I couldve done that but when I would have to script my own collision check..
Depends a lot on what you mean by "Class" and "->" there
Parent
I still don't fully follow what you mean by that
Objects are created by classes
Do you mean Object, the class, or object the concept
An object is an instance of a type, and classes are types
ye like in java the scanner class allows creation of scanner object
Okay, so yes, an object is a concrete representation of data defined by a class (or struct)
be careful, in Unity, Object and object are 2 different things
Unity is hard man
no it's not, you just need to know a few things
Hm btw could u help me with one small thing about unity
To be fair, almost every language as a capital-O Object class that everything derives from
Well, almost every object oriented language at least
no Objects in Haskell
I am having an issue in my unity project
I think I know why
but not sure how to fix it
yet still doesnt say what it is 👍
how to Do the things to paste 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.
// Being destroyed and recreated? Therefore its always going to put you in level two
IEnumerator DropPointGivers()
{
isDropping = true; // Start coroutine
for (int i = 0; i < pointCount; i++)
{
float waitTime = Random.Range(dropTimerMin, dropTimerMax);
Instantiate(pointGiverPrefab, transform.position, Quaternion.identity).GetComponent<Rigidbody2D>().velocity = Vector2.down * dropSpeed;
yield return new WaitForSeconds(waitTime);
}
isDropping = false; // Spawner Dropper dropped 10 flags and is ready for next wave.
if (isLevel2 == false)
{
isLevel2 = true;
FindObjectOfType<LevelManager>().LoadLevel2();
Debug.Log("Level Two");
}
else
{
FindObjectOfType<LevelManager>().Win();
}
}
This how to keep this script alive
Don't kill it
When switching scenes
Tell unity that
look at DDOL
what?
Dont Destroy On Load
but when i do that
Would I have to create some sort of loop
to allow the script to run well again when press play again
or Does it allow specific scenes for it to live
What?
you want to keep the Coroutine alive or the script alive?
What do loops have to do with things?
Because when play again if the script never dies it will never go back to level 1
basically
If you stop playing every object is destroyed
regardless of DDOL
Then use DDOL to keep it across a scene load then manually destroy it when you're done with it
no
oh
DDOL is exactly what it says on the tin. It makes an object not be destroyed on load
k thx
It marks the object to stick around when a scene change happens
!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 actually just bookmark the sites instead of calling the bot each time
true
just bookmarked 😛
hatebin is the best
Anyone?
i cant find any guide on unity 2023 collaborative and how to do it with other people
Use git or unity version control
I recommend the former
Not really a code question though. Better for #💻┃unity-talk
does it allow live collaboration git?
Nope
no such thing in unity
damn thats sad
well how to team create then??
guys ima gonna go crazy 😭
how can i fix thiss
so when i click on my game when the UI pops up the mouse disapears when i SPECIFICLY TOLD IT NOT TO IT STILL DOES
im only a begginer and no one has the same problem i do :c
https://hastebin.com/share/iguzijiroy.csharp
thats the only one that has it and i dont know where to put it so i just put it on the camera or the player
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i mean collaborate on a game project with people!!!!!
Git with github
That is the standard
Evenin' all. soooooo, I'm having a bit of a brain issue figuring out the logic on this script.
What I want it to do is for the 'end point' of the linerenderer to move back to its origin ( left side of the screen, pink character), but I can't seem to figure out code.
Could anyone point me in the right direction please?
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.
remove the Cursor.visible = false; line in start and it should stop.
like this ?
using == to compare two vectors is almost never true because of rounding. I suggest using Vector3.Distance(...) < 0.1f
== is perfectly fine for Vector3
it gets turned into Approximation
Actually, Vector3 overloads == to use Mathf.Approximately on all three components. It's perfectly fine to do
It's floats you shouldn't compare with ==
Yeah I can fix that once I get it 'snapping' back. 😕
No need to fix it. See above
Yeah I just read. lol.
Hi i have this code and i want the code to spawn a prefab in like 3x3x3 or 6x10x8 like you choose how many to spawn and i am getting stuck my code is under
[SerializeField] private GameObject boxPrefab;
[SerializeField] private float boxWidth = 1.0f;
[SerializeField] private float boxLength = 1.0f;
[SerializeField] private float boxHeight = 1.0f;
private float amountToSpawn;
void Start()
{
SpawnBoxes();
}
void SpawnBoxes()
{
if (boxWidth > 1 && boxLength > 1 && boxHeight > 1)
{
amountToSpawn = boxWidth * boxLength * boxHeight;
while (amountToSpawn > 0)
{
// Code to spawn them like 3x3x3 or boxWidth x boxLength x boxHeight
amountToSpawn--;
}
}
else
{
Instantiate(boxPrefab, transform.position, Quaternion.LookRotation(Vector3.forward));
}
}
Your StopGrapple() method is only called when the button is released, so once. You should convert it into a Coroutine.
Aaaah. Yeah that makes sense.
Thanks 🙂
try 3 stacked for-loops
may i ask why?
3 nested loops
I could be wrong about this, but the way I've seen this done before (usually on an x,y grid) is nested For loops (x, y, z) using your boxWidth etc. as the for loop 'target' amount.
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
//Instantiate here and set position to (x, y)
}
}```
Then it will Instantiate width * height objects.
The nested loops for the 3x3x3 would run like this with their indexes
0, 0, 0
Then 0, 0, 1
Then 0, 0, 2
Then 0, 1, 0
Then 0, 2, 1
Etc
It would give you all 3x3x3 coordinates
yea but what is a nested loop
Oh
Loop inside a loop
it spawns something but there is too many now my script looks like this
void SpawnBoxes()
{
if (boxWidth > 1 && boxLength > 1 && boxHeight > 1)
{
amountToSpawn = boxWidth * boxLength * boxHeight;
while (amountToSpawn > 0)
{
for (int x = 0; x < boxWidth; x++)
{
{
for (int y = 0; y < boxHeight; y++)
{
for (int z = 0; z < boxLength; z++)
{
GameObject boxToSpawn = GameObject.Instantiate(boxPrefab);
Vector3 pos = new Vector3(x * boxWidth, y * boxHeight, z * boxLength);
boxToSpawn.transform.position = pos;
}
}
}
amountToSpawn--;
}
}
}
else
{
Instantiate(boxPrefab, transform.position, Quaternion.LookRotation(Vector3.forward));
}
}
Subracting AmountToSpawn should be in the innermost loop
Also, you have an extra scope in there
The curly braces
Right after the for loop with x
AmountToSpawn and the while loop are not nessessary
yea i deleted it
but the spaceing is because of this cs Vector3 pos = new Vector3(x * boxWidth, y * boxHeight, z * boxLength); then the grid is 3 from each pilar
!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.
Apologies all, but I'm missing something really obvious here (been staring at it for a while).
My debug is only firing once and I'm not entirely sure why.
IEnumerator StopGrapple()
{
if (currentGrapplePosition != tongueRootPosition.transform.position)
{
currentGrapplePosition = Vector3.Lerp(currentGrapplePosition, tongueRootPosition.transform.position, Time.deltaTime * 8f);
Debug.Log(currentGrapplePosition);
}
if (currentGrapplePosition == tongueRootPosition.transform.position)
{
lr.positionCount = 0;
tongueEnd.SetActive(false);
Destroy(joint);
}
yield return null;
}
Your yield is completely pointless here
You're waiting a frame before doing nothing
Your lerp is messed up
You are multiplying an unchanging number by deltatime
How so?
The t parameter of lerp is supposed to increase or decrease between 0 and 1
Yours is going up and down randomly based on frame rate
https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html
MoveTowards may be more what you are looking for
Check out this link for more info
What you did is called "wrong-lerp"
https://unity.huh.how/lerp/wrong-lerp
Okay, thanks. Will take a look 🙂
Hello im tryna replace an item in a list when a value changes in a tmp_inputfield, the problem is that the newText string is empty, even though the onvaluechanged() function actually triggers
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
public class Answer : MonoBehaviour
{
[HideInInspector] public GameObject questionItem;
[HideInInspector] public int arrayOrder;
[SerializeField] TMP_InputField answerName;
[SerializeField] GameObject question;
private void Start()
{
arrayOrder = questionItem.GetComponent<Question>().answers.Count();
Debug.Log(arrayOrder);
}
public void OnValueChanged(string newText)
{
questionItem.GetComponent<Question>().answers[arrayOrder - 1] = newText;
}
}
can i get some help fellas?
Are you sure it is empty? I don't see any Debugs. Also why is questionItem of type 'GameObject' and not of type 'Question'? You could save yourself the GetComponent() call. Also use Debug.Log() to read the value of your inputField directly instead of using the parameter and see if that is empty as well.
tryna make a collaborate is it nromal to be uplaoding 15k files??
since the newText in inspector is empty so unity passes an empty string each times it calls it
yes one sec
You should use the Unity specific .gitignore file.
ah what does it do exactly??
ignore some files
well i have no idea how to uncommit to main now
it tells git which files to ignore, i.e. data that is generated automatically by unity
and its taking ages to upload
You do NOT want to upload a lot of the stuff you are pushing
show the newText in inspector
i am pretty sure it is an empty string
add
answerName.text
into your debug as well
okay one sec
the newtext is serialized so unity passes the value in inspector when it calls this method
Where do you call OnValueChanged
One other thing, you don't really want spaces in the project name. That can mess things up
Show
You're passing in empty string
yes, empty string
You probably want to use the dynamic version of the function
instead of passing in a hard-coded empty string
how do i do that
Choose the function from the "dynamic" section
which passes the value of the input
where is that
The same place you set the function this time
I figured it out. lol. I was being a moron and trying to do the 'snap back' in the wrong place.
Ignored files won't show up as changes in git status
should it be a txt documnet?
The thing that says "Text Document" is just Windows classifying the file based on some heueristic
it's completely meaningless/irrelevant
well
your os classify it as text document
it still shows me 13k files
what does
In git? Or windows
Commit the gitignore file 🤷♂️
ah..
Did you commit anything else yet?
did you name your file .gitignore.gitignore?
If so it's not named properly
it should just be .gitignore
Ahhhhhh, that would do it
should not be called that wth..
based on the screenshot the filename is incorrect
Yeah please turn on file extensions for the explorer
My guess is you have file extensions hidden in windows explorer
turn them on
That should be on by default
your right
turned it on
also keep in mind adding a gitignore after commiting won't do anything. The files would still be tracked.
it is .ignore.ignore wtherv
fix that
great
That is correct, and what you want
Most of the files are a cache of generated files for your game and the unity editor itself, which you do not need to save
Well i guess i wait untill github updates or shows the commit whtever it is
It's usually instant, once the files are uploaded from your computer
Make sure you Pushed the commit
Did you push it?
Last screenshot you hadn't even published the branch yet
woops
well all good now
hope if someone downloads this they can just open it and edit immediatly
dont want to go through some weird process again
They would need to clone the repo into a project
You need to push any changes you make, and they would need to pull them to see them
But the remote repo is created, and set up now
can anyone tell me how i can check if a function could be called in unity or it throws an error. in c++ you just do if( function() ) but idk about c#
gonna have to expand on that
wdym
wdym by check if it can be called
if it throws an error
for example if im trying to reach an item in a list that doesnt exist and it returns the outofbounds error, i wanna check that
can you gimme an example?
wait so if i do a try{} with the function in it, it will try to do the function, but if it throws an error it skips it?
so for you it would be
try
{
function();
}
catch (IndexOutOfRangeException e)
{
//do something on fail
}
in general though you'd put checks in to prevent the throw
so checking index is valid before trying to access
alr ty
wait
how will it be in the case of this error
can you show the code too
generally you want to avoid try catching throws in the first place
i havent coded your idea yet
wait i dont think i need to do catch {}
i tried the c++ method, but its not good, imma implement it with try{}
or do i?
if (questionContainer.transform.childCount > index + 1 && ...) nextButton...
I think that should prevent the error
ty man
this switch statement doesnt activate on the slash case. I printed the mySkill and it matches but the switch doesnt run.
Safest way is to just use enum or some sort of "id"
There might be a space or other "invisible" characters at the end of that string
Is textbox the display text component of a TMPInput?
Well actually the issue is that you're using a TextMeshProUGUI to interface with an input field, that's incorrect
index is the current question, not the total count
The field should be of type TMP_InputField
TMP_InputField adds a non-print character that isn't stripped with Trim(). You can manually cut it with:
.Replace("\u200B", "")
Or use the input field directly
yeah, but that check added is checking if the index is less than the amount of children then allow it (though i did write it the other way around)
otherwise you are asking for an index that doesnt exist
okay ty guys that fixed it
but it can allow it to go back past 0
ok lol, why are you having negative indexes?
well i can go to the previous question
i can do that also
add a check to make sure it's greater than 0 too then
Is there a way to use GameObject.Find() for inactive game objects?
There are plenty of ways to reference inactive objects. There is no way to use GameObject.Find as it explicitly doesn't work for deactivated objects
How can I reference inactive objects using scripts?
You should avoid GameObject.Find in general for many reasons, including this
It depends on the context.
Why?
GameObject.Find is very inefficient
it's also fragile, as it depends on object names which can change at any time in development
The preferred way is a direct reference in the inspector.
But again it depends on the context
void Reset()
{
GameObject.Find("Virtual Camera 1st person").TryGetComponent(out a1stPersonVirtualCamera);
GameObject.Find("Virtual Camera 3rd person").TryGetComponent(out a3rdPersonVirtualCamera);
}
```Yes, it is inefficient but I'm running it just once, not in `Update()`. The thing is if game object is disabled it can't get its component and I have null reference exception
It's like null.TryGetComponent(out a1stPersonVirtualCamera); and that's not going to work
so null check the result of the Find before calling TryGetComponent on it
So I was wondering if I can do something in case if game object is disabled
Alright, so there's no solution? 
why don't you just:
- do this once when they're still active and save the references?
- Have another object which directly references these that ISN'T deactivated, and get the reference from there
Why am I getting this error?
I have a steam_appid set to 480
This is my current code:
public class Texture2PFP : MonoBehaviour
{
[SerializeField]
private RawImage m_Texture;
private CSteamID userID;
protected Callback<AvatarImageLoaded_t> avatarImageLoaded;
ulong m_SteamID;
private void Start()
{
if (!SteamManager.Initialized) return;
userID = SteamUser.GetSteamID();
avatarImageLoaded = Callback<AvatarImageLoaded_t>.Create(OnAvatarImageLoaded);
}
private void OnAvatarImageLoaded(AvatarImageLoaded_t callback)
{
if (callback.m_steamID.m_SteamID != m_SteamID) return;
m_Texture.texture = GetSteamImageAsTexture(callback.m_iImage);
}
private Texture2D GetSteamImageAsTexture(int iImage)
{
Texture2D texture = null;
bool isValid = SteamUtils.GetImageSize(iImage, out uint width, out uint height);
if (isValid)
{
byte[] image = new byte[width * height * 4];
isValid = SteamUtils.GetImageRGBA(iImage, image, (int)(width * height * 4));
if (isValid)
{
texture = new Texture2D((int)width, (int)height, TextureFormat.RGBA32, false, true);
texture.LoadRawTextureData(image);
texture.Apply();
}
}
return texture;
}
}
I am trying to set a texture to a steam PFP, but its crashing out
get the reference some other way. GameObject.Find does not find inactive objects
google says I am missing a steam_appid file but i have it in there??
- Well, the thing is if one camera is activated then the other one is deactivated and vice versa. So one of cameras is always disabled by default.
- Uh, that's going to make more mess I guess
I'd have to create a new class to store references for deactivated game objects, it's rather faster to just manually assign them in inspector
I was wondering if there's a way to convert Instance ID to game object, something opposite to GetInstanceID();
you're overcomplicating this massively
make a script that references both of these obejcts, directly, through the inspector
Then you can do whatever you want with the references
share them with other scripts, etc.
Where though? I don't see it anywhere in this script. Unless it's m_SteamID, it's private and you never put a value into it, so it will be 0 by default
Well, this is Reset() method and it's supposed to assign objects in the inspector for me 
Why can you not just set them yourself
It was advised in this tutorial https://youtu.be/DETB4kieadc?t=105
Why deactivate the whole GameObjects instead of just disasbling the virtual camera components for example?
Oh, that makes sense, I'll try that, thanks!
Do you reset a component often enough that you want it to keep these references? This seems like a way overengineered way to solve a very specific problem that only works if your object is set up exactly like they've done
Thats not steam_appid, steam_appid is set in a txt file. https://kb.heathen.group/steam/steam_appid.txt
So the code isn't really related to the issue
I don't know, thats why I am asking honestly. been wondering why its crashing
Where exactly is it crashing? Because that code does nothing apart from running Start() when the game starts.
Do you have an exception occurring somewhere? You should post its stack trace here
In an if, when checking collision, how do I check if the first object collides with any object in the second object?
The code is this:
if (Collider2D.Equals(gameObject, deletionAreas))
{
Destroy(gameObject);
}
````deletionAreas` is a List.
Why are you using Collider2D.Equals?
Can you be more clear about what you're trying to do?
You want to check if a certain object is contained in an array?
What types of obijects are we talking about?
GameObject? Collider2D?
What is the type of the array?
this code isn't checking for any kind of "collision"
The code is for a bullet. I have two squares outside of the screen. I want the bullet to delete itself when it touches it (or an enemy/player, which I will add later).
it's just checking if two object references refer to the same object... sort of, in a really wrong way.
You should be using OnTriggerEnter2D or OnCollisionEnter2D
In the if, or as a new method?
I can't even find any sort of documentation for Collider2D.Equals. Where did you find that?
I tried doing "Collider2D" because someone on a unity forum post I found said to use that, but the latter part they used didn't exist, so I put the one that looked correct.
...you should probably do some basic tutorials on handling collision detection.
This whole question is a "throw this out and start from scratch"
I tried finding some but it was all videos instead of text.
hello, i am new to unity but i am very good at computer science and understanding coding ( at least i think so ). how would i use the new input system to return a value of the mouse's x and y coordinate?
make an action in an actions asset and bind it to mouse position, then read the value (details depends on which style of input handling you're using)
Tried doing Collider2D what? That's a Type, what were you trying to do?
how do i read the value exactly?
details depends on which style of input handling you're using
I just realized, I can do that without using colliders by just doing a "if bigger than x or smaller than y" check
Thanks, though!
2d vector
i think?
i binded delta mouse to a 2d vector action
not what I'm asking at all
sorry
Are you using PlayerInput?
Are you using the generated C# class?
Are you using InputActionReference?
You should probably find a tutorial for getting started with the new input system
ok first I'd like to ask why " GameObject playerObject = GameObject;"
=> trying to hover a gameobject from scene onto inspector doesn't work. (type mismatch of somekind?)
maybe the syntax is wrong (that used to be from find object with tag. ) but couldn't really assign that eithe.r
GameObject playerObject = GameObject;
If this is what you wrote that is 100% a compile error
yeah that should be. it wasn't though, there was this that checked null
^tagging is bad but I was in a hurry and couldn't assign shit. xd
how should I do it?
this tag I think doesn't find its way home, and it's the right title.
You talked about:
hover a gameobject from scene onto inspector
So are you drag-dropping? Or are you referencing it from the code?
drag dropping.
Because when it refuses to drag-drop into an object in the scene, it means the thing you're trying to drag-drop is an asset (prefab) that is not in the scene, and that's not allowed
I'm trying to drag an object from the hierarchy in the scene onto a prefab. :C
maybe that's not allowed.
Yes, because there is no guarantee the scene will exist when the prefab exists
right. but I do need the link from that object to the prefab (I'm using the prefab to spread a script that needs the player location).
maybe I'm going all about this wrong.
The code that Instantiates the prefab will have to pass the references you need at runtime, fully from the code, then
ugh.
spawn it, set it, forget it
right now it adds the script that asks for the reference to the object. That script needs that link, but I don't think I can assign things to a script from the inspector, and tagging is bad (and didn't work...)
there's other alternatives
but you'll have to assign it during runtime..
the only other alternative is to have the stuff u need packaged into the prefab already
I have the script packaged in the prefab, but that's one I cannot drag to. otherwise I do not know what to add to it. x-x
Who talked about finding, when Instantiate returns the object that was just created?
GameObject inst = Instantiate(prefab, pos, rot);
inst.GetComponent<SomeScript>().thing = something; // injection of the reference
no the things you drag must also be inside hte prefab
or u assign it after the fact ^
aagh. I'm too tired for this x_X
this seems like a reference to the object that you instantiate, not an object outside the instantiated object?
heres a reference manager i use
taking some of its component.
That's what you want
in start i find all my references.. during the loading screen
You want to set the variable of the object you just spawned
ooh!!
then afterwards they're assigned so i dont need to call expensive find calls or w/e
amaznig
just that once
shit I should've done that. it's a little late now.
note, thats just 1 method.. and it does use find calls.. which somepeople don't ever use
so I add a component variable "Player" and then assign it... but I'd have to find the other object to do that.
in my experience i use them in start and awake functions (just once) and its been a pretty decent system
The object spawning your prefab should have a dragged-in reference to the thing you want
and then pass it to the spawned object
object spawning prefab aka the enemyspawn manager?
noooo x_x
I can't follow.
maybe just scrap that whole thing. it's getting super late.
it would truly take some time to get to the bottom of this/understand the thing fully
this script worked a while ago
it stopped working out of nowhere with basically no changes. x_x
? wat I thought the whole point of a prefab was reusing it accross multiple scenes
No. Not really
It's for instantiating copies
You CAN do it across scenes, but they are useful even in one scene
I thought I would only do a ui control in one scene, prefab it and then reuse it in other scenes...
That sounds like a not good use of prefabs honestly
so I dont have to redo that ui control in a canvas over and over again
Just use DDOL
Oh, maybe I misunderstood
You mean copy the same canvas/ui into multiple scenes? That makes sense
I thought you meant copy the current state of the ui to a prefab at runtime, then instantiate that state in a new scene
Like the ui control is actually a text with separator and part of the text is clickable etc. text is dynamic (so monobehaviour) and I want to use the whole thing as a control in multiple scenes. SO I thought of making it a prefab so the monbehavior follow around to manage the dynamic text as well so I can use the whole control in multiple scene
And no it's not to copy the state it's for code/gameobjects reuse
Just to clarify to make sure the context of the discussion is understood: Im going to have a breadcrumb in this format: $"{myFief.parentRegion.name} > {myFief.parentDepartement.name} > {myFief.parentArrondissement.name} > {myFief.ParentCounty.name} > {myFief.ParentBarony.name} > {myFief.name} > {myBuilding.buildingType} > {myBuilding.buildingID}" and each of these parts between the > would be clickable. It's something I'll use in every UI so you can quickly navigate and so far I'd do one scene = one UI so that control would be used all over the game
ngh. I tried this fancy way to assign it but it remains null..
Kinda ruins my plans if I can't prefab it and simply drop it in multiple scenes
guess 'm gonna have to alter script to just shoot down lmfao. xD
wait that wouldn't even help
what on earth is going on though. I saw these things shoot bullets for 10 hours straight and suddenly it's null x_x
What is null? There's a few things that could be null there
A prefab is an asset that represents a blueprint for a gameobject with specific components holding specific values. Some values won't work (like serialized references to scene objects), but anything other than that should.
So what you're saying should be fine
the bullets I assume, since they aren't instantiating. I tried switching the script from tracking the player, and something stayed null so, yeah. probably bullets. :/
I think I debug logged it about them bullets as well. ah, and I did check that the instantiated objects dont have that reference in the inspector at runtime.
Don't assume, check.
thanks for your help 🙂 I can continue my cunning plans then
Imma send the script your way. Idon't think it's the problem though.
They mean that many things could be null it there like bulletPrefab or bulletprefabname. So you should debug that or put a breakpoint and inspect
https://hastebin.com/share/ujimiboqij.java null at 43. instantiator: https://hastebin.com/share/hofizecuta.java
My Unity projects are often breaking with doing a push from one developer and a pull from another developer's machine. We're using PlasticSCM, but it's still happening.
also where is bullet2 in the editor ?
breaking in what way?
Assets/Bullets/Bullet2 ?
The most common issue is the components will be missing references to objects
And file IDs messing up
that bullet prefab vanishes at instantiate
it's assigned to the prefab.
looking like this at idle.
These sound like issues with meta files not being updated/checked in properly
Even after deleting the whole folder on my desktop, when pulling the project, I was still having problems with losing references to game objects in some components
Yes exactly ^
How do I fix this?
what. suddenly it works. I made no changes.
Make sure anyone making changes is properly checking in all modified files including meta files
what's wrong with git ? It doesnt work with unity or something ?
not a criticism Dudesss, just a subtopic because you remind me of why unity doesn't show me git as possible source control in the edit preferences
Git works perfectly fine with unity
It is the standard
or maybe not. x_x gah
had a nice view of screen full of bullets for a video presentation 2 hours ago.
basically no changes->they are gone. x_x
wdym by "vanishes at instantitate"?
you can see in that image, that they are no longer assigned.
two images, first of instantiated objects which no longer have an assigned bulletPrefab
and second of one which has it assigned to the prefab of those instantiations at rest.
no longer assigned means you have code assigning them to null
that makes sense, but I don't think..
I think the editor is confused because it shows two bullet prefab fields instead of one
it's unclear to me if this is a component on a bullet or on a thing that spawns bullets
There's only one field
this is a component on a thing that spawns bullets.
so you're spawning the thing that spawns bullets?
yeah.
Ok so show:
- the script that spawns this thing that spawns bullets
- the inspector for the thing that spawns the thing that spawns bullets
- The Bullet Pattern 1 script
- the inspector for the prefab that is referenced from the first script.
Wait you're doing this:
GameObject bulletPrefab = Resources.Load<GameObject>("Bullets/" + bulletPrefabName);
these two scripts are here
in other words the variable you have in the inspector is pointless
why on earth are you doing this?
What I mean is that the bullet prefab name still shows despite the prefab being gone
this is my later attempt to fix what was already broken, sir.
the two fields are completely unrelated
if you have a direct reference to the prefab why are you doing any of this Resources.load and prefab name stuff?
just do Instantiate(bulletPrefab)
this is all I have on the spawn that spawns the bullet spawners.
which prefab is the bullet spawner?
GameObject bullet = Instantiate(bulletPrefab, transform.position, rotation);
this is what I had in the script before, and now even.
yes but you're using a different bulletPrefab variable here
one you got from Resources.Load
this was used before I had resource load.
ok well go back
I can do that yeah.
which of these prefabs has the issue?
the holymines.
ok great so - now with the resources.load removed, what happens?
what inspector are we looking at here?
the uh, holy mines, sir.
yeah.
Some instance from the scene?
search your whole project for bulletPrefab
for jumping with a character controller, for a very simple movement 3D game can i just make it a very fast cooldown instead of checking if it's grounded
because nothing in the code you shared thus far would ever change that
yeah, that's why it's so confusing.
are you 100% sure the exact copy of HolyMines that is referenced from the spawn manager is the one you showed the inspector for?
like did you click on HolyMines from this screenshot?
yes
That's what you should do to look at it
Also is that screenshot from the copy of the SpawnManager that's in the scene? Or elsewhere?
on the scene.
Can you show the full !code for BulletPattern1?
📃 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.
Since it's a public variable I'm wondering if some other script isn't assigning it
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I'm trying to figure out how to search the whole thing for it rn
neither of the search bars (hierarchy) and assets show anything
Replace this:
public GameObject bulletPrefab;
with this:
[SerializeField] private GameObject bulletPrefab;
I mean in your code editor
this is a good idea though, you'll get a compile error if there's another reference somewhere in your code, which will immediately find it for us.
no compile error after adjusting serialized field
the only thing I can imagine then is just that we're looking at the wrong instances
Okay, so, let's see a screenshot of the entire unity window with the HolyMines prefab selected and the inspector visible
(This will make it possible to check several things at once)
yeah this is madness. XD
Now, double click on that Bullet2 prefab in the inspector, and show another full screenshot of what comes up
Can you show the code for BulletDamage and BulletCollisionHandler
they can affect this? uh oh.
shouldn't be able to 🤔
this is much better than mystery shows on the discovery channel. Cant wait to know the cause 🙂
If the prefab was destroyed I would expect "Missing (GameObject)" not "None (GameObject)" in the inspector
Yeah, thats what I'm thinking, but at this point we're out of things that should be the problem so I'm willing to look at things that shouldn't
loopk fine to me, at least in terms of this problem
Okay, right before the Destroy call, add this log:
Debug.Log($"{gameObject.name} has collided with {other.gameObject.name} and is self-destructing", this);
Then go through the process that gave you the empty inspector parameter and see if this was ever logged. If it is, show what it prints
Okay, those are the clones and they're after the error so it doesn't seem like it's that
This leads me to believe you have two instances of this script. If it doesn't instantiate the bullets then there wouldn't be logs at all
which script?
Let's put in another surgical log:
The line before you instantiate the bullet, the place the error is at, put this:
Debug.Log($"{gameObject.name} is attempting to spawn bullet prefab: {bulletPrefab}", this);
have now gone through all the scripts involved: no duplicates in the assets.
Put the log above the line before the error. It'll give you info as to what object's doing the spawning before the error occurs, and when you click the log it'll highlight that object in the hierarchy
Click on the first log, just once. See which object it highlights.
Then click on the second log and see which object it highlights.
Are they different objects?
Do either of them have parents
yes
about that, how do see what ithighlights? cause clicking on things generally doesn't show anything to me...
OH i see the problem here
thank you that was really quick
The ,this at the end of the log will tell unity which object to highlight when you select the log
So these logs will show something in the hierarchy when you click on them
as long as that object still exists at least
oh rght. it does show the mineclone.
I may be detecting some flash of light from those mines. maybe they are destructing.
Do both logs show the same object
yes.
Can you show the full inspector of that object, during play mode. Even if it has to be multiple screenshots
should I still send something?
No, we've found the problem
what, really?
Duplicate component
Since you asked, ^
Do you AddComponent it when you spawn it
yes.
well there you go
yes. I do
oh no XD
aahahahaha
I'm dying.
thank you I can finish this project in time XD
I can get a grade man. XD
I'm trying to destroy tiles in a tilemap by using a tilemap collider 2D and setting the tiles to null based on the hit position as follows:
{
if (boxCollider != null)
{
Vector3 hitPosition = Vector3.zero;
foreach (ContactPoint2D hit in collision.contacts)
{
hitPosition.x = hit.point.x - 0.01f * hit.normal.x;
hitPosition.y = hit.point.y - 0.01f * hit.normal.y;
tileMap.SetTile(tileMap.WorldToCell(hitPosition), null);
}
}
}
```
It somewhat works, but the object is for some reason capable of resting on the tiles without destroying them at low velocities
You can see that if I move it again, it continues destroying them
Any idea how I can fix this?
Maybe your offset is setting the wrong tiles to null
Log the to-be nulled tile and see if the point is valid (not null already)
There shouldn't be any reason for a nulled tile to have made a collision.
🙂 I enjoy trying to learn from the issues other users encounter. It gives me some additional ways to resolve an issue if something similar happens to me
Whjen I started to code as an intern Id peruse the technologies my employer was using for a good part of the day (docs/stack overflow/msdn/etc) so I would have a bank of problems/solution in my head of problems I would potentially encounter and some way I could fix it like that
private void OnCollisionEnter2D(Collision2D collision)
{
if (boxCollider != null)
{
Vector3 hitPosition = Vector3.zero;
foreach (ContactPoint2D hit in collision.contacts)
{
hitPosition.x = hit.point.x - 0.01f * hit.normal.x;
hitPosition.y = hit.point.y - 0.01f * hit.normal.y;
//check if the tile at the hit position is null
if (tileMap.GetTile(tileMap.WorldToCell(hitPosition)) == null)
{
Debug.Log("Tile is null");
}
tileMap.SetTile(tileMap.WorldToCell(hitPosition), null);
}
}
}
Is this approach for debugging valid? Because I'm definitely getting some debug logs
That means your hitPosition isn't the expected tile
Log the hit position for more info on what you made it set to null
Honestly not sure what to do with this information
I can't figure out a trend really?
@wintry quarry We're uploading all our changes and there's still missing references. For us in this case, it's our NetworkManager gameobject in our scene that's missing all the references.
Okay, I seem to have fixed it using OnCollisionStay2D, which I tried to do earlier, but accidentally used OnCollisionStay 🤦♂️
This comment might be unwelcome for you, but just FYI unity docs says not to use Collision2D.contacts but to use GetContacts as it may cause problems down the line
Thanks for the heads-up, I modified it to use that instead
is the best way to move the player setting their velocity or is it using addforce
why is this arc too long?cs //Draw upper arc Quaternion tiltRotation = Quaternion.AngleAxis(-scientist.yVisionAngle / 2, scientist.visionPosition.right); Handles.DrawWireArc(scientist.visionPosition.position, tiltRotation * scientist.visionPosition.up, upLeftEndpoint - scientist.visionPosition.position, scientist.xVisionAngle, scientist.visionRadius);
also its not quite connecting
how would 1 go about adding boundaries for the player in a 2d game
colliders?
"a 2d game" is quite vague but assuming you are using 2D physics, then 2D colliders would be the way to go.
2d side scrolling type game
i have an unactivate polygon collider to keep my cinemachine camera wigthin boundaries
if i activate collision with that would that work?
assuming your character actually moves via physics, it will interact with colliders, yes
Right after pulling my project with free download PlasticSCM, my NetworkManager looks like this. I need to run the scene, stop the scene, run cm update with PlasticSCM, change scenes in the editor, and go back to the original scene, then it gets populated
Is there a quicker way to do this?
idk if this is not #archived-networking
Maybe I'm not supposed to run the scene right from the beginning, and there's another way to build the project
is there a way to make the colider only collide on the edges but not on the main thing?
use an edge collider
you could also use 4 box colliders
or a single polygon that is in a "picture frame" shape
didnt know that was a thing
how do I fix this error?
whats the main difference between late update and update?
i think late update is run after the frame ends
wait no
late update is run after Update functions have been called
you're trying to access something static. start off by asking yourself why that variable is static
learning new things every day
i made it static so I could call it from other scripts