#archived-code-general
1 messages ยท Page 80 of 1
The way I understood quaternions is that there's two set of angle, and two set of distance. The angle helps rotate initially, then the distance tells you how far you are on that angle. Then repeat for the second angle, which gets rid of the third dimension entirely (effectively removing gimbal lock)
I'm going to be honest
that doesn't help me understand them more
I'm getting more of a feeling for using them though.
It's complicated, have you try using TransformPoint?
yes it happens with TransformPoint too
What about LookAt()?
yup
๐ฅฒ
it's fine. i've been dabbling in Quaternions a little bit. I don't need to fully understand them just yet, I just need it to work... i can understand them later
Quaternions are fun and powerful if you really understand. It's like a matrix4x4.
So i'm just trying to change color of a 2D Sprite Renderer, and then here's what happens:
They turn invisible.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Teleporter : MonoBehaviour
{
public GameObject opposingPortal;
public bool ChangeColor;
public Color32 colorToChangeTo;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player") {
other.gameObject.transform.position = opposingPortal.transform.position;
if (ChangeColor) {
other.gameObject.GetComponent<SpriteRenderer>().color = colorToChangeTo;
}
}
}
}
Code for refrence.
oh wait i'm stupid
there's something about the alpha
hey, because I'm making an Interact script and I don't know why it shows an error
code
error
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
i did but the error is still there
it should be underlined in red in vs code now though which should make it more obvious what the issue is
then it isn't configured
I have configured it now and still nothing
just configuring it won't magically fix the issue. it will just show you where the issue is.
**using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Interact : MonoBehaviour
{
public GameObject col;
public GameObject text;
void Start()
{
text.SetActive(false);
}
public void OnTriggerEnter(col)
{
text.SetActive(true);
}
}** Code i dont know where is the problem just error
configure vs code so it will show you where the issue is
if you cannot get vs code configured then consider switching to visual studio which is much easier to configure and is actually still supported
what?
which part of that did you not understand?
hah was it @leaden ice and @heady iris i was talking with about the mapmagic2 issue? praetor your suggestion to reach out to denis worked - funny update to the story - so i reached out to denis asking if he had any tips - in the meantime, i figured out how to write a custom generator node for mm2, and had a hacky solution that just used it to write to a scriptable object - but then denis got back to me, we exchanged some emails, and he said that spline output node should be working? i pointed out where it wasn't, he apologized and sent a new (working) version of SplineOut, lol
all
you know what the word "configure" means, yes?
yea
then follow this guide to configure vs code #archived-code-general message
(click the link that says VS Code and follow all of the instructions)
ok
bingo (:
someimes (especially if you paid for it!), you can just say hi
Nice
OnTriggerEnter should be public void OnTriggerEnter(Collider other) . You are missing the declaration of the type of your parameter.
hey
anyone here know about MFPS or ulogin pro???
pls dm me if u know
Hi. One question, does anyone know if there's a way to select a gameobject at runtime if it doesn't have a gameobject? Like, select it as if it was in the editor but do it in a build
can anyone hleep me maek a enemy in my game cuz i am not good at coding and like idk almost anything about it and im just using chatgpt to do it and i cant find any good enemy tutorial tings
welp ig nobody can helep me atm
- don't crosspost
- go through some structured courses to learn wtf you are doing. nobody here wants to be your personal tutor.
there are courses pinned in #๐ปโcode-beginner
good luck. don't expect help with your AI generated code here though
Hey, this might be a bit of an abstract problem but I'm making an RTS and I want to make it so that when you set a unit to attack another unit, it will automatically find a a soldier to target while staying in formation. Here, for example, each soldier will be assigned to a target with an index across from it, which is pretty easy when dealing when units of the same size (and using dot products to check if the order should be reversed)
But the problem arises when you try doing this with two units of different sizes
with the current approach, they will end up crossing each other
so this is what happens with units of the same size
and this is with different sizes
sorry for the spam
but I'm looking for a way to have them find a target directly across (or at least one that doesn't require crossing)
each unit has values for unit size, depth and length
Using Buttons with both Sprite Swap and keyboard input, is this possible?
What about this approach?
that could work, though I'd imagine it would be quite a heavy calculation for large units
Yeah, it would be quite expensive for huge squads. I suppose it could be sped up by somehow dividing the squad into subsquads. If the performance was an issue, you could try some quadtree implementation, so you could check only units from a particular map area.
If you want a simplified approach, I would suggest calculating targets only for corner soldiers, and then try to set other targets analogically. If a unit from position x1, y1 targets a unit from position x2, y2, then a unit from position x3, y3 would probably want to target a unit from position x3-x1+x2, y3-y1+y2. The results should be decent as long the formation is regular - any bigger noises could make targeting look noisy.
hmm alright, I'll try to do something like that
thanks!
hi : D
maybe
just maybe
i hate matrix in C#
is there any easy way to multiply 2 matrix who isn't 4x4?
Depends on the type, what do you use to store these matrices? float[,]?
Does any one know how i can make a flashlight type of light in a top down 2D game so that it wont render bojects if they are outside of thie flashlight making it almost pitch black
so, any other matrix ever created?
matrices in C# are still just matrices
see how matrices work in mathematics and you'll stop hating "C# matrices"
that's a really really really hard thing you are trying to achieve
you could try using the experimental 2D lighting that comes with URP
Is it possible that you only hate the matrix because you don't understand how the matrix works?
or https://www.youtube.com/watch?v=rQG9aUWarwE this
note: it's in 3D, but I know it can be converted to work with 2D because I did so in one of my projects
In this miniseries (2 episodes) we create a system to detect which targets are in our unit's field of view. This is useful for stealth games and the like.
Source code + starting file:
https://github.com/SebLague/Field-of-View
Support the creation of more tutorials:
https://www.patreon.com/SebastianLague
https://www.paypal.me/SebastianLague
seems like it
I am trying to setup a VR script that looks in a certain direction and if it hits a box collider in layer 8 that it will print out Looking at Watch
The problem atm is if I am not looking at the watch it will still say looking at watch. Anyone know why?
hmm
myb i should inspect the code a bit more lul
also, why do you 1 << 9 if you want the 8th layer?
// Bit shift the index of the layer (9) to get a bit mask
also
uhhh
it's because you say "else, debug.log("Looking at watch")"
it will debug the same thing no matter what
omgosh
it happens
so with the set code it only does not looking at watch
could hit.distance be the cause?
screenshot hurts ... !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.
void Update()
{
// Bit shift the index of the layer (9) to get a bit mask
int layerMask = 1 << 9;
// This would cast rays only against colliders in layer 8.
// But instead if we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
//8layerMask = ~layerMask;
RaycastHit hit;
// Does the ray intersect any objects excluding the player layer
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
{
//Vector3 Position = new Vector3(transform.position.x + 5, transform.position.y, transform.position.z); //Sets position on where inventory spawns
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Looking At Watch");
//GameObject instance = Instantiate(InventoryTest, Position, Quaternion.identity);
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
Debug.Log("not Looking At Watch");
}
}
So many comments in your Update() method. If your layerMask is never going to change anytime during your game runtime, might as well cache the result and use it as a reference.
Or make your LayerMask an inspector value to change/adjust.
I'm instancing a bunch of game objects at runtime. Is it possible to make a prefab of the scene(partof) and still keep the instanced prefabs link intact?
atm it won't change but I have plans to chance it during run time
also the comments are temporary just throwing stuff at the board and hoping it sticks
Yes?
Would you know the reason object is not seeing the watch?
Does the object you expect to be watched have layer set?
yes
set it to layer 9 and called it watch
isn't transform.TransformDirection(Vector3.forward) the same as transform.forward?
Same result, yeah (maybe not bit by bit due to impresicion. Transform.forward uses Quaternion * Vector3 multiplication, Transform.TransformDirection does Matrix4x4 * Vector3)
is this on the camera?
does the camera/head have a collider?
it's on a VR headset so I believe that is needed. Not sure though
this is connected to a head camera that has a collider
well then I'm 99% sure it collides with the camera's collider
hmm if it's on the camera wouldn't that not be part of the objects it hits?
make sure to shoot the ray outside the camera's collider, or do Physics.IgnoreLayer or something like that and ignore the camera
yes
it doesn't always do that
actually, it almost never did that for me
but it can't have a rigidbody because that messes with the VR hands
@quaint pine okay, I hoped so... How ?
if I create a gameobject by instantiate and reference a prefab it looses its reference once its in the scene
It should work... You have debug.DrawRay, whatwhere does it hit?
yes when I start the game on unity I can see it move around but I don't see it in the head set
so it aims and changes color
but doesn't activate for some reason
classic x/y problem...
hey, does anybody know how to create the instance of GameObject without Instantiating it and without changing the original prefab?
private void SpawnEnemy()
{
Vector3 currentPos;
while (true)
{
currentPos = new Vector3(TupleRange(spawnPos.x), spawnPos.y, TupleRange(spawnPos.z));
GameObject enemy = enemyPrefab; // need to change this one
enemy.transform.position = currentPos; // or/and this one
Bounds bounds = enemy.GetComponent<SphereCollider>().bounds;
Vector3 topLeft = new (bounds.min.x, bounds.min.y, bounds.max.z);
Vector3 topRight = new (bounds.max.x, bounds.min.y, bounds.max.z);
Vector3 bottomLeft = new (bounds.min.x, bounds.min.y, bounds.min.z);
Vector3 bottomRight = new (bounds.max.x, bounds.min.y, bounds.min.z);
if (OnIsland(topLeft) && OnIsland(topRight) && OnIsland(bottomLeft) && OnIsland(bottomRight)) break;
}
Instantiate(enemyPrefab, currentPos, spawnRot, enemiesDocument.transform);
bool OnIsland(Vector3 position) => Physics.Raycast(position, Vector3.down, 1f, LayerMask.GetMask("Island"));
}
what
We look at your code that only tell us that the raycast hit hits only your watch, but when you say "activate" what do you mean? Are you trying to invoke something on your watch?
?
so the idea behind it
what do you mean "without Instantiating"?
not being created in the scene?
is that when the player looks at the watch a hud will appear
How are you referencing it? When you instantiated a prefab object with prefabs inside, all of your prefab should remain linked.
what does activate at this moment
what I am trying to do right now is just get it to say debug.log("looking at watch")
"Looking at watch"
then just Debug.Log(hit.gameObject);
yes, in my variant I do not create it in the scene, but I change the original prefab, which I don't really want to do
so we can see what it hits
then just initialize a GameObject
oh yea let me check that out
GameObject go;
i have no lcue how this list error is connected to me invoking an event, i need help
that gameObject must be the same as prefab, so that I can GetComponent then
'RaycastHit' does not contain a definition for 'gameObject' and no accessible extension method 'gameObject' accepting a first argument of type 'RaycastHit' could be found (are you missing a using directive or an assembly reference?)
GameObject go = prefab;
@quaint pine The problem occurs at the moment I instansiate the objects that will become nested in a parent prefab later. The child objects are all named (clone) in the hierarchy and has lost their references.
^
Debug.Log(hit.transform)
is what i meant
that's exactly what I did
ah ok
You're reading the stack trace backwards, the topmost line is the deepest one, not the inverse. So your issue in in Enemy.MyTurn, Enemy.cs:76
and you are doing go.GetComponent instead of prefab.GetComponent?
Ideally I would want them intact with the prefab linkage + a bunch of overrides
sure:
GameObject enemy = enemyPrefab;
enemy.transform.position = currentPos;
Bounds bounds = enemy.GetComponent<SphereCollider>().bounds;
and how does this change the prefab?
but line 76 is a bracket
Wait... you're not calling Instantiate?
and there arent too many nor to less
ofc no
they don't want it in the scene
look:
private void SpawnEnemy()
{
Vector3 currentPos;
while (true)
{
currentPos = new Vector3(TupleRange(spawnPos.x), spawnPos.y, TupleRange(spawnPos.z));
GameObject enemy = enemyPrefab;
enemy.transform.position = currentPos;
Bounds bounds = enemy.GetComponent<SphereCollider>().bounds;
Vector3 topLeft = new (bounds.min.x, bounds.min.y, bounds.max.z);
Vector3 topRight = new (bounds.max.x, bounds.min.y, bounds.max.z);
Vector3 bottomLeft = new (bounds.min.x, bounds.min.y, bounds.min.z);
Vector3 bottomRight = new (bounds.max.x, bounds.min.y, bounds.min.z);
if (OnIsland(topLeft) && OnIsland(topRight) && OnIsland(bottomLeft) && OnIsland(bottomRight)) break;
}
Instantiate(enemyPrefab, currentPos, spawnRot, enemiesDocument.transform);
bool OnIsland(Vector3 position) => Physics.Raycast(position, Vector3.down, 1f, LayerMask.GetMask("Island"));
}
Instantiate creates a copy. You can't access information within prefabs if they're not initialized, otherwise you're directly modifying the "source" prefab object.
Yeah, it's a Unity bug that causes the exception to be reported at the end of the block it was thrown in. So, move was either too low or too high and is out of bounds of your cards array
It's spamming out this Null
I do not want to instantiate it, because player can see it then
that while(true) looks like that could break.
exactly ... I don't really want a copy. I would like the reference intact
you mean to avoid it?
You can't create an instance of a GameObject without instantiating it in the scene. GameObjects only exist in the scene . . .
Insantiate has 4th parameter
so it hits nothing?
yea
create UIDocument for example and create gameObject here
that's because you didn't set up the layers correctly then
but the weird part is it's changing colors
are you 100% sure that the watch is on the right layer
i still get the error eventho move must be bigger than 0 and smaller then move.cound
Instantiate(enemyPrefab, currentPos, spawnRot, enemiesDocument.transform); enemiesDocument is UIDocument
can you resend the code, the newest version
I can create GameObject without instantiating it and then get whatever I want from it
That's because this condition is evaluated left-to-right. Put the bounds check before you access the array
hey everyone, im currently working on a platformer, but there is one thing that does not work. In editor everything works perfectly, but as soon as I build the project some of values feel wrong so i cant make some of the jumps
cards[move%cards.Count]
use Time.deltaTime
the fps in the editor is infinitely higher than in the build version
// Update is called once per frame
void Update()
{
// Bit shift the index of the layer (9) to get a bit mask
int layerMask = 1 << 9;
// This would cast rays only against colliders in layer 8.
// But instead if we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
//8layerMask = ~layerMask;
RaycastHit hit;
// Does the ray intersect any objects excluding the player layer
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
{
//Vector3 Position = new Vector3(transform.position.x + 5, transform.position.y, transform.position.z); //Sets position on where inventory spawns
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Looking At Watch");
//GameObject instance = Instantiate(InventoryTest, Position, Quaternion.identity);
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
Debug.Log(hit.transform);
}
}
or is it the other way around I don't remember
i see, thanks
and if you are using physics, do FixedUpdate()
or else you'll have unpredictable results
I think what I want to do is only possible inside the editor and not at runtime
when you test, it should lag a bit I guess
I usually do them in fixedUpdate but i must have messed up with timed events
well of course it changes the color to white since it never hits anything.
aight gl
Time.deltaTime becomes Time.fixedDeltaTime when used inside FixedUpdate() method.
yes
Instantiate can only create clones not references to prefabs ๐ฆ
yes
yea
bummer
You don't reference the prefab bcuz the prefab is not suppose to change . . .
how is that a problem exactly?
how to I then create clone without Instantiate method?
you can't
It's used as a template . . .
why do you not want to use the Instantiate method so much
I already answered that you can't . . .
What exactly are you trying to do?
Do you need an actual GameObject or a MonoBehaviour class. You can create instances in memory with c# classes . . .
what exactly do you need though
I have written it few times
this is starting to sound alot like you need ScriptableObjects
great, what
my scenario is a bit complicated.. I got an ingame-editor that can create levels by using instantiating prefabs... Now I want to load up the game in the editor, create a map. Grab an entire map or part of a map in the hierarchy and create a prefab of it (this works fine) but all the items inside the new prefab are only clones.. would be nice if the prefab references where intact and only a couple of overrides applied to them
I'm so confused, do 2 people have the exact same problem? lmao
seems like it ๐
then I could change a chair or something.. then it would change the chair prefab.. and update all the rooms that use the chair
the prefab references are intact wdym
yes you can already do that
just change the chair
in the editor
If I had done this in the editor.. it would work. But the problem is that I am creating the world using my own in-game editor
so I fire up my in-game editor.. grab my room that i want prefabed. But the chairs and stuff are all just clones by now
since they are create using Instantiate
I think you need a "Load" function
yes... that's a good idea. I guess I could write an editor script to use my existing load function
๐
Wouldn't it be easier if you'd just create a prefab of the level, so that you can just drag and drop into your scene?
it appears they don't want that functionality though
If you've written it then point others to that post so new people coming in have context when trying to help fix your problem . . .
I need to create enemyPrefab in the Scene on the the hexagon, not rectangle. So I have (float min, float max) x and z positions (tuples) to create like if it's rectangle.
But to avoid creating enemyPrefabs where they just fall nowhere, I do check if they are on the floor with Physics.Raycast with while loop, if they are, I just break that while loop and create enemy on that nice position, where they do not fall.
The Raycasts are gone from enemy's bounds, but to get those bounds, I should GetComponent<SphereCollider>() of enemyPrefab. To do it I need to Instantiate it. But? It instantiates in the scene then. To avoid that I just create GameObject instane, but this also changes original enemyPrefab.
And now the question: How can I do the same without changing original enemyPrefab position?

you are doing something secondary that changes the prefab's position
Ideally, if you know that the enemy must spawn on hexagon shape, then I would create a manager to keep track of all existing hexagon shape, that the enemy can spawn on. Then your manager would expose method implementation to receive coordinate, which will check any existing hexagon shape that matches that coordinate and spawn it. Otherwise, skip.
ah
I see
@gray mural you need to change the position after you instantiate the object
sort of like this
then player sees enemy
what do you mean?
player sees it
enemyPrefab
Disable the gameobject after you spawn it, so that the player can't see it?
it's the same
@quaint pine yes.. that is pretty easy, the problem comes later if I want to update some item inside the room.. it would have lost its reference
How would you update the item if it didn't have reference initially???
You'd only lose reference if you override the reference. Then that's a dangling reference problem.
yes, that's why I was asking about how to Instantiate without making a copy ๐
private void SpawnEnemy()
{
Vector3 currentPos;
GameObject enemy = Instantiate(enemyPrefab, currentPos, spawnRot, enemiesDocument.transform);
while (true)
{
currentPos = new Vector3(TupleRange(spawnPos.x), spawnPos.y, TupleRange(spawnPos.z));
enemy.transform.position = currentPos;
Bounds bounds = enemy.GetComponent<SphereCollider>().bounds;
Vector3 topLeft = new (bounds.min.x, bounds.min.y, bounds.max.z);
Vector3 topRight = new (bounds.max.x, bounds.min.y, bounds.max.z);
Vector3 bottomLeft = new (bounds.min.x, bounds.min.y, bounds.min.z);
Vector3 bottomRight = new (bounds.max.x, bounds.min.y, bounds.min.z);
if (OnIsland(topLeft) && OnIsland(topRight) && OnIsland(bottomLeft) && OnIsland(bottomRight)) break;
}
bool OnIsland(Vector3 position) => Physics.Raycast(position, Vector3.down, 1f, LayerMask.GetMask("Island"));
}
didn't proofread it
but this is the logic
it's exactly the same
except it does what you want it to do
you could also put this line GameObject enemy = Instantiate(enemyPrefab, currentPos, spawnRot, enemiesDocument.transform); inside of the while loop
Needs enemy.SetActive(false); until it finds a place to stand on.
nice, you instantiate enemy on Vector3.zero position
ah
and how pc's work
the entire script
is swept
from top to bottom
in one frame
you won't see the enemy spawned at 0,0,0
the while loop has to finish in the frame and if it doesn't, you get a frame drop, simple as that
fps drop*
I just gonna let it as it is, I sure do not need enemyPrefab's position
The player does see that frame
Hey guys i'm new here ๐ i was trying to follow this to save data instead of using playerprefs https://www.youtube.com/watch?v=aSNj2nvSyD4 the project im working on will be my first completed one its very small lol im still learning.. anyways the problem im having is ArgumentException: Empty path name is not legal. followed tutorial just to see if i could get it working but... yea
In this Tutorial, we're going to make SAVING DATA GREAT AGAIN! Using the JsonUtility class to save data in the JSON format is going to be a breeze and it's just a good idea to do so!
== WRITTEN TUTORIAL ==
Blogpost: https://url.kaupenjoe.net/yt11/blogpost
== ASSETS & DOWNLOAD LINKS ==
GitHub Repo: https://github.com/Tutorials-By-Kaupenjoe/Sav...
it gets spawned at 0,0,0
then it gets manipulated
ok I gonna prove it to u bro
but if I had 50 fps, then =>
you don't understand how processors work and how they carry out instructions
the entire script
is done in one frame
meaning that if the last bit of the script "moves" the enemy, that's where the enemy is going to be
this is so painful to explain and i gotta get ready so bye, can someone else take over
You wont see anything from a frame until that frame has completely finished processing
its a flash blink of an eye
i'm physically hurting after this exchange, I'm glad you figured it out tho!
thx osmal 
so anyone here good with saves using json? its for a small first project i just dont want to use playerprefs
Osmal said that you wanted to say the full time, but didn't, cause you are too shy, I see now
they have a bad rep
You gotta be trolling at this point
lmao
nope
Imagine the pain teacher had to suffer to teach kids computer science...
I think it's a language barrier
I was saying what Thicc was saying too
I don't want to imagine such horrors
because of my english or yr c#? 
so uhhh
a little bit of both, plus, my english isn't the best either! :)
it seems to be failing to get any of the components that should be there
How did you learn about C#? @gray mural
and since im getting like 20000 errors i cant read them all
but sorry if I somehow hurt you man, i didn't mean to, thx for help anyway
!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.
Make a development build -> Attach profiler and process. Debug from there.
ArgumentException: Empty path name is not legal. followed tutorial just to see if i could get it working but... yea
googled how to make games
where weere you supposed to attatch process again?
i can remember how to attatch profiler
You never call SetPaths() anywhere in this script, meaning your paths will have their initial value always (empty strings "", set on lines 9 and 10)
so the path = on line 25 doesnt set them?
It does, but as path is empty, it sets an empty string
Look at the tutorial. They might do SetPaths(); in Start or something, you missed it
okay
gezzz haha i got it thanks so much yea he did in start .....
new to programming i just don't want to learn bad practices
ik json files can be tampered with but I dont care as long as i can save what i need to for bigger projects thanks for the help ๐
Just stop the task . . .
ok so the issue seems to be that
the component can not be accessed from another script for some reasons
it can be accessed from the script in the gameobject the component is in
well, how are you trying to retrieve the component?
i am using gameobject.getcomponent
show your code.
enemyhitboxes= enemyylist.transform.Find("hitbox").GetComponent<BoxCollider2D>(); one of the many examples that brings an error
this only happens in build mode not in editor
i think its an access issue
as in the scripts cant access anything in another gameobject for some reason
Is there an easy way of resetting a ScriptableObject to the starting values?
Rightclick -> Reset
I mean in code
Same
?
Without the right click
Looks like its for MonoBehaviour only
It sets all serialized fields to their default values or runs whatever overrides youโve implemented
Nice
So not ScriptableObjects?
ScriptableObject implements it too
https://docs.unity3d.com/ScriptReference/ScriptableObject.Reset.html
however i'm not sure if calling it manually is going to reset it's serialized fields
Its just a Unity message, I mean its not a part of ScriptableObject
So idk if calling it manually would do anything
Btw, you should not be overwriting serialized values. So in a properly implemented SO, this wouldnโt come up
Did you try it? Because I doubt it works in this case
you would have to implement the reset ofc
Yeah I dont know if manually resetting every member in the code is what hes asking for
maybe like this ```cs
public class MySO : ScriptableObject, ISerializationCallbackReceiver
{
[SerializeField] private float foo;
public float Foo { get; set; }
private void Reset()
{
Foo = foo;
}
public void OnBeforeSerialize()
{
}
public void OnAfterDeserialize()
{
Reset();
}
}
No
Just use Resources.Load to reload the SO
Update: it was actually the provided default settings like โthresholdโ that were stopping it from working. Which explains why I got zero errors when debugging it in VS. Anyway, I just messed around with the settings, despite what the included PDF, instructed and voilร ! thank you for your help yesterday also @somber nacelle @simple egret ๐
Why do I have infinite while loop?
private void SpawnEnemy()
{
GameObject enemy = Instantiate(enemyPrefab, Vector3.zero, spawnRot, enemiesDocument.transform);
while (true)
{
enemy.transform.position = new (TupleRange(spawnPos.x), spawnPos.y, TupleRange(spawnPos.z));
Bounds bounds = enemy.GetComponent<SphereCollider>().bounds;
Vector3 topLeft = new(bounds.min.x, bounds.min.y, bounds.max.z);
Vector3 topRight = new(bounds.max.x, bounds.min.y, bounds.max.z);
Vector3 bottomLeft = new(bounds.min.x, bounds.min.y, bounds.min.z);
Vector3 bottomRight = new(bounds.max.x, bounds.min.y, bounds.min.z);
if (OnIsland(topLeft) && OnIsland(topRight) && OnIsland(bottomLeft) && OnIsland(bottomRight)) break;
}
bool OnIsland(Vector3 position) => Physics.Raycast(position, Vector3.down, 1f, LayerMask.GetMask("Island"));
}
I have done as guys before suggested me
because you typed while(true) and your if statement at the bottom is never true to break out of the loop
well when could the bounds on the enemy sphere collider change during that loop?
since this is not a coroutine that is yielding no other code besides this loop is running for the duration of the loop
this one worked very well:
private void SpawnEnemy()
{
Vector3 currentPos;
while (true)
{
currentPos = new Vector3(TupleRange(spawnPos.x), spawnPos.y, TupleRange(spawnPos.z));
GameObject enemy = enemyPrefab; // need to change this one
enemy.transform.position = currentPos; // or/and this one
Bounds bounds = enemy.GetComponent<SphereCollider>().bounds;
Vector3 topLeft = new (bounds.min.x, bounds.min.y, bounds.max.z);
Vector3 topRight = new (bounds.max.x, bounds.min.y, bounds.max.z);
Vector3 bottomLeft = new (bounds.min.x, bounds.min.y, bounds.min.z);
Vector3 bottomRight = new (bounds.max.x, bounds.min.y, bounds.min.z);
if (OnIsland(topLeft) && OnIsland(topRight) && OnIsland(bottomLeft) && OnIsland(bottomRight)) break;
}
Instantiate(enemyPrefab, currentPos, spawnRot, enemiesDocument.transform);
bool OnIsland(Vector3 position) => Physics.Raycast(position, Vector3.down, 1f, LayerMask.GetMask("Island"));
}
this is IvokeRepeating
that doesn't change the fact that if your if statement is never true the loop will never end meaning no other code will run. so if that if statement is not true the first loop how could it ever be true on following loops?
that one works perfectly, another one has infinite loop
then use the one that works if you are so sure it isn't an infinite loop
break your if statement down into its components and find out which part is failing. Debugging 101
oh
you might also want to consider visualizing your physics raycasts so you can see where they actually are instead of making assumptions ๐
haha, yeah
good advice
To Assume : making an Ass out of U and Me
Gizmos
lmao
gizmos, debug.drawline, a debugging library like vertx's debugging package
I'm trying to follow a tutorial and im not sure where ive gone wrong for this last part to come up as an error
you need to find just one
I completely missed that
or make it GameObject.FIndGameObjectsWithTag("LogicManager")[index]
(I hope it is array)
but you'd better not
been skipping back and rewatching this video for the past 30 mins trying to figure that out
thank you
Also better to split that into 2 statements just in case the Find fails
how would one go about doing that?
GameObject go = FindGameobject...
if (go != null)
logic = go.GetComponent<...
else
Debug.Log("Find faild");
just in case you messed something else up
does Debug.DrawRay work in non-update function?
yes, why wouldn't it?
cause it does not work in my case
if (OnIsland(topLeft) && OnIsland(topRight) && OnIsland(bottomLeft) && OnIsland(bottomRight))
{
Debug.DrawRay(currentPos, Vector3.down * 2f, Color.green);
break;
}
else
{
Debug.DrawRay(currentPos, Vector3.down * 2f, Color.red);
}
well keep in mind if you still have an infinite loop how do you expect the frame to progress to actually draw the rays?
and how often are you calling the DrawRays? because you haven't set a duration which means it only lasts for the frame you call it on
i mean infinite might be a bit much, but you can provide a decent number to the duration parameter to keep it up for a bit
thanks
How do I scale UI properly across all/the majority of mobile devices
Cuz it seems like a lot of phone/tablet screen resolutions are very very different
should I just aim for a few mobile devices when creating an app instead of all of them
Canvases have options to scale them with the screen size. Then it's a matter of anchoring your UI objects correctly so they're always in the right place whatever the screen size is
you can use the CanvasScaler in "Scale With Screen Size" mode.
and then, yes, it's all about anchoring and positioning the pieces correctly
This should help a bit:
https://www.youtube.com/watch?v=be4gDI8RZ2U
Learn all about the Canvas Scaler! The Canvas Scaler comes by default whenever you make a Canvas in Unity, but many of us don't fully understand how it works or what it does. When making a game, ensuring your UI scales reasonably across multiple different aspect ratios and screen resolutions is critical.
In this video we'll dive deep into each...
Taking some time to learn how the different anchor modes work is very worthwhile
Hey, I have a question regarding combining multiple rotations, so if anyone has knowledge in the area, I would really appreciate some help.
I am making a 3D game that has the player walk around spherical planets. This is the player rotation code (in the Update method) that smoothly rotates the player based on my input vector:
if (input.magnitude >= inputThreshold)
{
float targetAngle = Mathf.Atan2(input.x, input.y) * Mathf.Rad2Deg;
rb.MoveRotation(Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0f, targetAngle, 0f), rotationSpeed * Time.deltaTime));
}
And this is the code for the player movement, which is in FixedUpdate:
if (input.magnitude >= inputThreshold)
{
rb.velocity = transform.forward * speed * Time.deltaTime;
}
And this is my poor attempt to align the player to the ground using a raycast's normal (which is inside FixedUpdate):
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit))
{
transform.up = hit.normal;
}
Understanding and utilizing Quaternions is my weakest area in game dev, so all of my attempts of using things like Quaternion.FromToRotation and Quaternion.Lerp have led to very broken results. If anyone has a solution or could even point me in the right direction of how I could achieve this surface alignment system, I would be very grateful :)
sorry, long question ;_;
Setting transform.up should do the trick.
If you do want to compose Quaternions, you can multiply them together. This gives you the result of applying both rotations.
However, rather than raycasting to the ground, I would rather just calculate the vector from the planet's center to myself.
otherwise, gravity will point all over the place as you walk up a slope
also, Vector3.down will shoot a vector in the -Y direction. I'm not sure if that's what you want.
Not sure what the following code is trying to do.
if (input.magnitude >= inputThreshold)
{
float targetAngle = Mathf.Atan2(input.x, input.y) * Mathf.Rad2Deg;
rb.MoveRotation(Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0f, targetAngle, 0f), rotationSpeed * Time.deltaTime));
}
Also, raycasting down will never give you a correct up. This is what you are trying to define. ๐
if you are standing on the "bottom" of a planet, it will shoot a ray into space
Like @heady iris said, you should use the closest planet to define the down. You could alternatively, use a whole bunch of calculation to add the gravity and figure out the highest gravity.
Oh! You're definitely right, that would be much smarter
"input" is just a vector2 thats defined by the horizontal and vertical axis', and this gives a rotation based on the input direction. i use MoveRotation because I want the rotation to be smooth, similar to how it feels in animal crossing (my game is a 3rd person game)
alright so I have this now in a seperate script:
[SerializeField] private Transform planetCenter;
void LateUpdate()
{
Vector3 playerToCenter = planetCenter.position - transform.position;
Vector3 newUp = -playerToCenter.normalized;
transform.up = newUp;
}
this does align the player with the planet's center, but since its directly modifying transform.up it just ignores the input-based rotation code I had before, and I'm not sure how to get around that
Hello, I have a question, why does the "itemsInfo" list not appear in the editor if it is public?
Its not having the attribut System.Serializable
I see, thank you very much!
yep yep -- you have to explicitly tell C# that this type can be safely turned into data (and retrieved from data)
I am building my project via BuildScript on a Github runner.
I would like to build for Pico and Quest.
Unfortunately I can't get both features (Pico Support, Quest Support) to work at the same time and neither can I get the controller profiles.
Can I change the OpenXRPackageSettings.asset via script?
if I want to use a canvas Ill do something like Public Canvas canvolini, but I want to grab a specific element on the canvas. What variable do I use for that. I want to get an image\
There are certain scripts that allow you to give them a specific object's method that they will call if a certain condition is met. How would I go about making a custom script take in a method?
Here is an example of what I'm trying on the XR Grab Interactable component.
it's a UnityEvent or UnityAction
hey everyone, does if im using IEnumerator as timer does it mean that it depends on frame rate
i use it to set values but main action goes on in fixed update
do you mean you're calling StartCoroutine and passing the result of calling your function to it?
yes, coroutines yielding will be dependent on the framerate because they are updated every frame. but the same can be said for a timer in update. if you mean will it vary based on different framerates then it can possibly vary slightly based on how long the last frame(s) of the waiting time take
StartCoroutine(MyTimer()) or w/e
yes like that
then there is no need to write my timer in update, right?
yeah im using it
up to you, there's really no difference in the amount of time the timer will be. it's just a matter of whether you want it to be a coroutine or in update ๐คทโโ๏ธ
if you yield a WaitForSeconds, then the coroutine will be resumed once that much time (scaled by timeScale) has passed
Okay, i was just a bit worried that it will mess up how my physics run, thanks guys
That worked, thank you.
so, i got a small tower defense game goin on where you can freely place walls to block enemies, the walls work by having the component navmeshobstacle with the carve option ON, but now i want to add "flying" enemies which are supposed to just ignore and go over walls like theyre not even there. How can i achieve this with the walls blocking the navmesh?
Layer masks?
yeah, you want to add a new kind of area
so do i just add another navmeshsurface2d to the scene?
Oh, you're not treating the walls as obstacles but carving a zone out
ah, obstacles can't be restricted to just one area type
if you use the new AI Navigation package, you get Nav Mesh Modifiers, which I'm pretty sure can target just one kind of area
o wait
aaa
is this a third-party thing? I don't recognize NavMeshSurface2D
i dont think so?
yeah, but I didn't think it had a separate surface type for 2D
so should i just change how the walls work?
can you show me this nav mesh surface?
...what is this?
oh wait, is that from NavMeshPlus?
yeah, this is third-party
the github one
lmao, i like the readme image
get that pepper
i honestly did that so long ago i dont evenremember
i have no idea about how this thing works
i just use the 3D navmesh with sprites lmfao
but yeah, if you switch to the new AI Navigation package, you can get Nav Mesh Modifier Volumes
which can target specific kinds of areas
so, you'd have a Flyer layer that isn't affected
well, it shouldn't be that bad :p
is that just in the package manager?
what version of unity are you using?
2020.3
AI Navigation only left experimental in 2022, iirc, but it is available back to 2019
guess what was only made possible in unity 2021

back in 2020, you have to manually edit the package manifest
extremely goofy
fuck me, no more flying enemies
it's not hard by any means, but just goofy
although
since you do have this NavMeshSurface2D
?
i wonder if you could just put down two of them
but the nav mesh obstacle would hit both...
is the game top down or sum?
yes
this is straight up not worth my time honestly
actually, I am curious
is there a component named "nav mesh modifier" ?
if so, you're good
cool, there you go
that's what you'd be getting from the new package
I guess they've been backporting the features to this NavMeshPlus thingy
the modifier volume would probably be the easiest to use
you give it a volume and then tell it which areas to affect
i remember trying to use it and having trouble with it, i dont remember exactly why though
oh wait, that might require you to re-bake the mesh
guess its worth a shot
what do you mean?
like. the wall's mesh?
the navmesh
so i'd have to rebake it everytime i place a wall
doesnt sound to complicated
or destroy it i guess
it's not bad, yeah
ok... ill try switching out the obstacle component for the modifier and see if the wall still actually works for ground enemies
wait, the navmeshmodifiervolume is only for 3d right?
you'd need to read the docs for NavMeshPlus to be sure; I'd expect it to work
ill just use the normal navmeshmodifier for now
oh, "volume" just means you give it an explicit region that it works in
i think the regular modifier is based off of the thing you attach it to
it does nothing, enemies do not see the wall so they just move forward instead of avoiding it
@heady iris you still there?
tried it with the volume too that also didnt work
@heady iris ??
transform.localRotation = Quaternion.RotateTowards(Quaternion.LookRotation((follow.position + follow.forward * 2.5f - transform.position).normalized, Vector3.up) * Quaternion.Euler(0, 0, follow.localEulerAngles.z), rotateSpeed * Time.smoothDeltaTime);
Why when I add Quaternion.Euler(0, 0, follow.localEulerAngles.z) does the Z axis start flipping by 180 like it has gimbal lock or something, even if the local euler angles are 0? if it's Quaternion.Euler(0, 0, 0) shouldn't that equal Quaternion.identity, which multiplied by anything would just result in the same value?
i can't tell you too much more; I don't know how this package behaves
guess i wont have flying enemies for now, thanks for trying to help
i am having immense trouble parsing this
because follow.localEulerAngles.z will flip around between -180 and +180. It's not really a good idea to read back euler angles from the transform
best to use your own float variable
follow the z rotation of the object
why doesn't it show it flipping in the inspector when I select the object it's following!?
so matching its roll, basically
If you really must use follow.localEulerAngles.z then I recommend using https://docs.unity3d.com/ScriptReference/Mathf.DeltaAngle.html to kind of "normalize" it
the stuff you see in the inspector is not really the same as localEulerAngles (though may be an equivalent set of euler angles)
yeah, you see global stuff in the inspector
Nah it's local
My comment is more that euler angles are not unique and the inspector doesn't necessarily show the same set of euler angles as .localEulerAngles
@leaden ice so uh, I'm a bit confused again. I have this to track the z rotation:
public float zRot
{
get => m_zRot;
set
{
m_zRot = value;
while (m_zRot > 360)
m_zRot -= 360;
while (m_zRot < 0)
m_zRot += 360;
}
}
private float m_zRot;
```It's only ever set through zRot.
However now it constantly spins as soon as I rotate the z axis, however before just reading the transform z axis it would not do that.
Show the rest of the code?
Sorry, I also changed the rotation code because the camera could not rotate fast enough to match the Z axis, it's actually fine if the z axis rotation is instant. This is the code that I'm updating the rotation on:
void LateUpdate() {
transform.localRotation = Quaternion.Euler(0, 0, follow.zRot) *
Quaternion.RotateTowards(transform.localRotation,
Quaternion.LookRotation((follow.transform.position + follow.transform.forward * 2.5f - transform.position).normalized, Vector3.up),
rotateSpeed * Time.smoothDeltaTime);
}
shouldn't this rotate the camera to be the z rotation, then apply the second RotateTowards rotation?
and doesn't it doesn't, and it doesn't make sense that it would, but my question still stands. Shouldn't this set the z rotation then apply the other rotation?Quaternion.LookRotation return Quaternion.identity if the from rotation is the same as the to rotation? so shouldn't it essentially be quaternion.euler * quaternion.identity?
and even if it didn't shouldn't it still be fine and not constantly spin it?
also, this is how I'm setting zRot:
private void WSADQE_performed(InputAction.CallbackContext context)
{
m_preOrient = context.ReadValue<Vector3>() * rotationSpeed;
m_preOrient.x *= pitchModifier;
m_preOrient.y *= yawModifier;
orient = Quaternion.Euler(m_preOrient);
}
private void WSADQE_canceled(InputAction.CallbackContext context)
{
orient = Quaternion.identity;
m_preOrient = Vector3.zero;
}
private void Update()
{
transform.rotation *= orient;
zRot += m_preOrient.z;
transform.position = shipRB.transform.position;
}
so i have a public int score in a script attached to a game object in game scene which updates TMPro Ui on game screen so you can see a score. i want to use the value of score after the ball falls and resets you back to menu save it and list it as highscore in mainmenu. i have a json script and a playerdata script. I'm new to coding of course lol but if you want scripts let me know
main issue is how can i get the public value of score right before reset and save it. i cant seem to access score from other scripts
!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.
this is movement and score tracker
reset script
Json saving script
PlayerData script
idk if this needs to be in code advanced or not lol
think i need to seperate the score tracker from movement code first of all right?
i also thought this project was really good for me lol because it was just a paddle movment ball drops evertime it hits plus 1 point then if it falls go to menu and show highest score
in what way can't you access the score from other scripts?
well if i try to use score as a value its not found
public void SetHighScore()
{
GetComponent<TextMeshProUGUI>(scoreText);
highscoreText.text = "HighScore: " + highscoreText.ToString();
}
you are not accessing the score here
you are getting a text component and then setting its contents
also, this would just set the highscore to be the result of turning the highscore text object into a string
that does not make sense
there isn't even a GetComponent overload that looks like that (unless it's some undocumented nonsense)
also yes
I'm kind of drunk right now so I completely glossed over that, lol
you invoke GetComponent on something
No, the generic overload returns a value and doesn't take one.
It's being implicitly invoked on this
there is a one-argument form of GetComponent, but that's so you can pass it a Type
it's non-generic
ye
๐ 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.
this is how im tracking and getting the score and then setting score added the last part of the code after i asked this question ๐ then here is the other restart code
yes, and that code is very ill-formed
yea im very new to coding...
first game i want to do a restart menu game score and a way of saving highscore and showing on mainmenu
thats it so its like all the basics
i was thinking i need a score manager
have a resart script and movment script to seperate it all
that's a good idea, ye
Surely this does not compile.
If you're not getting errors underlined in your IDE, you need to configure it !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
yea ik it dont ๐
im getting red lined
i had something earlier and was just trying stuff while looking stuff up
ok I've narrowed my problem down.
All this code is in the LateUpdate() method.
Why does this spin infinitely on the z axis:
transform.localRotation =
Quaternion.RotateTowards(transform.localRotation,
Quaternion.AngleAxis(follow.zRot, transform.forward) * Quaternion.LookRotation((follow.transform.position + follow.transform.forward * 2.5f - transform.position).normalized, transform.up),
rotateSpeed * Time.smoothDeltaTime);
as well as this:
transform.localRotation = Quaternion.AngleAxis(follow.zRot, transform.forward) *
Quaternion.LookRotation((follow.transform.position + follow.transform.forward * 2.5f - transform.position).normalized, transform.up);
but this does not:
transform.localRotation = Quaternion.AngleAxis(follow.zRot, transform.forward);
Shouldn't the first two examples essentially do what the last example does, then apply the look rotation after the z has been rotated? (It also spins when I multiply the look rotation by the angle axis)
also, follow.zRot
ill try to seperate it and get it working
One is creating some complex compound rotation from multiple things with random values and subtractions, and the other is a simple, seemingly fixed, rotation
so how would I rotate the z axis independently from the other calculations?
i also have another issue i create newscript name it and try to add it to emptygameobject and i get Cant add script component 'ScoreManager' becuase the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.
hey i have this code:https://hatebin.com/ebgrusosnb but when the player respawns on line 283 it gives me an error saying object reference not set to an instance of an object
Show your code.
have you considered just using a compound transform and not doing all this complexity
Do you have other compiler errors still'?
you mean like apply several rotations sequentially?
I mean have a nested transform, one that controls the Z axis, and one that does whatever else you want
I'm not sure if that would work. I'm controlling the camera rotation, so I need to control the z axis along with the x and y. The x and y by themselves work great actually, it's just when I try to control the z as well as x and y.
no // did the job but just fixed it somehow? just renamed the class and the file name to SManager and it fixed it even tho they was the same to begin with becuase i just created the script...
Hey I have an Issue, I get this error message:https://hatebin.com/ecnkzcusgo whenever I shoot a player that has been respawned. Can anyone help?
i tried networking and nobody responded
you just posted it
i reposted it
i posted about it hours ago
probably because this error alone isn't helpful
maybe review #854851968446365696 how to post a proper question to the issue
Hi!
I've been trying to make my code as modular as possible, and I've realized I may be able to take it further.
I, for instance, want to create a few "condition scripts" (On Collision, After Time, etc.) and several "function scripts" (SetActive, Do This, Do That, etc.) and be able to attach these two types of scripts any which way I please.
So for example, once the condition is met on the "After Time" script, it would execute any of the "Do This" scripts I've attached to it.
Problem is, I can't just attach any script I please -- I can only reference specific named scripts. Google hasn't yielded any results for how to go about this, if it should even be feasible or a good idea.
Is this feasible/a good idea, and if so, where/how can I begin to learn this? Thanks
you could use delegates
Thank you very much, this sounds like exactly what I'm looking for :)
This sounds like ravioli in the making combined with https://en.m.wikipedia.org/wiki/Greenspun's_tenth_rule
is there any way to create a dynamic script to find a possible army formation with a number of soldiers and a position to make the formation around, and return a list of the vectors for the soldiers?
Yes
how would I do this. I tried using a for loop to create it, but it doesn't avoid obstacles
Well, you could check locations for collisions in your for loop and exclude those
wouldn't that leave some soldiers without a spot to go to?
You could maybe continue looping until all have found a spot
ok
if the number couldn't be perfectly squared, how would I find the best possible fit?
How do you define โbestโ?
the most box like, and evenly spread out, so that its as square as possible
You can only find the best solution by trying all solutions, but you can get to a good enough solution by limiting the search range or simply appending all soldiers without a spot to the end of that box formation, turning it into a slightly rectangular shape
anyone got a solution for ignoring folders on build?
Build automatically ignores all assets that are not referenced by a scene which is included in the build
If you want to exclude a folder from the asset database, suffix it with a ~
cool figured this was the route I would have to go down after looking at some threads online.
my build sizes are still hitting approx 100mb is it not possible to shrink it more? (simple project, 1 scene, have some packages I have pulled in from the asset store but not referencing any of those scenes in build scenes).
Use Asset Bundle for better control of whatever is being add to the build. Note that 100mb is nothing. Non compress texture of 2048x2048 is 16mb. (2048 x 2048 x 32 / 8). That being said, those should be compress and have a size of around 2mb.
these are builds that should literally have just code, no textures, audio etc.
another variant should have prefabs but no textures, audio, etc.
I assumed I would be able to get them into the 30mb or less range
Does anyone here know stuff abt Mirror Networking?
my bad
Reading a bit more, it seem that you should be able to get in the range of 20mb-40mb. You are doing something wrong. You could try to use https://docs.unity3d.com/Packages/com.unity.build-report-inspector@0.1/manual/index.html to inspect the content of your build.
I am having an issue trying to calculate the pitch angle of a calculated Vector3 direction. I know I am doing something wrong and I am absolutely too brain-fried to see what the issue is. Attached is a crude diagram that shows what I am trying to do, where CT and LO are both Vector3s. I need the red pitch angle readings returned as a float.
First, I subtract the two vectors to get a direction that points from CT to LO:
Vector3 calculatedDirection = LO.position - CT.position;
From this point, I have attempted a lot of things including Quaternion.LookRotation and FromToRotation, but the end result is incorrect. With the code I have tried, the position of CT on the XZ plane alters the reading of the pitch angle when the angle is supposed to equal zero.
https://docs.unity3d.com/ScriptReference/Vector2.SignedAngle.html
CT is your from, LO points are your to
How can get the top and left screen space points of the screen space bounding box on a mesh in the scene, so I can position a UI there like in this example, red representing the screen bounding box.
How would you get the screen bounding box? That sounds bit tricky atleast
Yeah... that's why I came here hah
I thought that maybe Camera has a built-in function that does something similar to that
I need it to be compatible with Vector3, but only account for angle change along a YZ plane relative to CT. Assuming that both CT and LO can move positions, the only angle I care about is the pitch difference. If CT's Y position is below LO's Y position, the angle should be a positive angle value, and any change in relation to the positions of either should not effect the angle so long as the Y positions of both remain the same.
Now that I think of it though it's probably some pretty complex math.
You pretty much have to iterate over each vertex of the mesh to get it, maybe not that complex but computationally intensive. So if there is any other way to position the UI elements that satisfies you, Id go with that
Alright, thank you!
you can reconstruct the Vector2 to use only the y and the z of your position new Vector2(yourObj.z, yourObj.y);
I will try that, thank you.
I changed it, z first then y
since z is technically your x axis
I tried using Vector3.SignedAngle, but it did not have the correct output.
Vector3 signed angle needs the correct axis that you are rotating along, but if itโs only going to be on a single axis, itโs easier imo to just use vector2 signed angle
Unfortunately, that also gives output that does not achieve what I need. But thanks for trying, I'll just try again later when I am not so tired, maybe I will figure it out then.
Atan2 will definitely work for this float Angle = Mathf.Atan2(LO.y - CO.y, LO.z - CO.z) * Mathf.Rad2Deg;
is it possible to make some calculations run on gpu?
hey guys ๐
so any help with nullreference errors in only build mode?
the issue seems to be that my scripts cannot reference anything outside its own gameobject
Hi, can anyone help me figure out what is wrong with my code or give me some good resources? I'm trying to make a yo-yo game but the physics have been really hard.. Currently i'm working on a rope that can expand and contract and keeps the yo-yo tether to a finger. The rope pretty much works sometimes, but it spazzes out like crazy pretty often and doesnt really obey gravity.. also the yoyo starts spinning very quickly
any references to components in its gameobject doesnt give erros
Could be an execution order issue. But anyways, not much we can help with without errors/code.
!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.
Sure. Compute shaders.
the problem is that i have about 40 scripts and i dont think its gonna be too helpful to post all of them
i do think can bring the error logs and the parts applicable though
Start from posting the error. Then the code that is relevant to it.
NullReferenceException: Object reference not set to an instance of an object
at generalmovementscript.Start () [0x0014e] in C:\Users\Admin\New Unity Project (2)\Assets\scripts\generalmovementscript.cs:100
(Filename: C:/Users/Admin/New Unity Project (2)/Assets/scripts/generalmovementscript.cs Line: 100)
Do you need a 100% physically accurate simulation?
@cosmic rain it doesn't need to be accurate, but i would like for it to be somewhat convincing
basically i have no idea, as long as the yoyo works pretty much correctly i think it will be fine
i could post the entire thing but i am doubting that it'll actually help
Logically thinking, enemyyList object doesn't have a child named hitbox.
oh that was just bad naming practice sorry
enemylist isnt actually a list its just one
i was trying to consider multiple enemies at once but then realized that i didnt need to
@cosmic rain here is what it looks like right now
https://i.gyazo.com/df61565d04f00b97c338b9c247fc3e8f.mp4
i mean enemies have hitboxes
which the code is referencing
that's nice, does the enemyyList object have a direct child named hitbox?
yes
thats the strange part im saying
I am pressing ๐ฝ to doubt
So what is the issue according to this video?
this is the part im confused on
am i supposed to add a line that instantiates those and if so what is it
we have no idea what you're doing, or what objects you're looking at
it does so the error isnt happening in the editor only in the build
this is the one for the supposed enemy
Do you **want ** to instantiate them..? There's kinda no point in asking us about it.
like im dont know what you actually mean by instantiating it
So are you spawning these enemies at runtime? Or do they all exist in the scene from the very start?
so enemyyList is player2? Are there many of them or only one?
there is just one
yes they exist in the scene from the very start
by instantiating i assume you mean that i create those objects
lots of things.. but gravity doesnt seem to affect the yoyo properly
there is supposed to be a hitbox though
and there is one so this error doesnt happen in the editor
i think i should test something rq because i found something that seems weird to me
because it seems to be able to recognize another gameobject it seems?
wait check for null for the different components
At what point? It does look like it's going down due to gravity when you're not applying any force(presumably).
oh i think that it might have to do with the execution order of child objects compared to regular scripts
do you mean in that childobject?
yeah
the object itself returns null so
its kinda obvious what would happen if i wanted to return a component from it
which is why i added that line
the components were not getting recognized
so i added a line to check if it was the object itself or just the components
basically the issue is that on a slight contraction the yoyo goes flying into the air
the controls for the game are extend and contract of the rope
also the yoyo gets a -Y velocity that builds from the beginning of the simulation to -7000 within a minute (this is unintended)
that is weird, I really cannot see anything wrong right now, you are sure that the variable enemyList is correctly assigned right
How are you applying force/velocity to it? There doesn't seem to be anything relevant in the script you shared.
try running idk another find as well possibly
yes im pretty sure about that one
for another child
for another child?
loop and log all the children of the object. That might give some clues.
yeah also it is generally suggested to not use Find
i can do that by getchild right?
yep thats why im using it
foreach(Transform child in enemyyList.transform)
Debug.Log(child)
hold on
Mainly this line in that first gdl.space
var vy = Input.GetAxisRaw("Vertical") * 20f * Time.deltaTime;
The blob that the string is attached to that is stationary has this, which does affect the string a bit.
https://gdl.space/raw/afezetebec
I don't see that line anywhere in this script.
That being said, moving a transform directly, could be messing with physics.
i think could also be that it doesnt like stop the velocity
when it reaches the end of the line
so it just builds up velocity
sorry i think i put the wrong code.. just realized i pressed ctrl z a few times
here is the code on the rope object
https://gdl.space/raw/fobugatexi
wdym by that? the velocity does just keep increasing into the - on Y
why the hell is my editor taking 5 minutes to reload script assemblies
when you dont move it right
?
F, happens, restart unity if it gets too absurd
the velocity is just increasing constantly and doesnt seem affected by the input
i would suggest rather than setting the rigidbody to the one of the points
to simply use an addForce or smthing to simulate the tension
rb.AddForce
That's the code from before.
I don't see anything related to velocities/force in here.
The only things affecting movement/position I see are these lines:
startPoint.position = fragments[0].transform.position;
endPoint.position = fragments[fragmentCount - 1].transform.position;
fragments[i].GetComponent<Rigidbody>().position = Vector3.zero;
And it would make sense that they break something, since you're setting the position directly.
yeah... that was the only way i could get the string to connect to the yoyo and the blob
endPoint.position = fragments[fragmentCount - 1].transform.position;
var vy = Input.GetAxisRaw("Vertical") * 20f * Time.deltaTime;
activeFragmentCount = Mathf.Clamp(activeFragmentCount + vy, 0, fragmentCount);
for (var i = 0; i < fragmentCount; i++)```
here, var vy is input, yes?
ig?
I recommend learning first how real world yoyo physics work, what forces are acting on each object and on the rope itself at each point in time. Then research the limitations of unity physics simulation and consider how to implement it.
Honestly, it's not something I'd do as a beginner
sorry this was probably not a good first project idea.. but i appreciate the help
yep, just imagin right
if a yoyo just teleports
imagine its gonna keep going fasteruntil it reaches terminal velocity
mostly the same in unity
except id know if theres terminal velocity
it sounds really hard to implement lol
i didnt think id really have to think about real forces
Unity physics mostly follows the same rules
If you don't wanna think about it, might as well avoid using physics at all
you could implement something similar without physics true, will it be accurate? no... but also thats how like idk line simulations work in lets say scratch and stuff
so either you use physics for basically everything or no physics at all
https://i.gyazo.com/b5155241759010735b8dbed10d0f1cef.mp4
this is interesting
Having a yoyo act close to real life analogue would require physics calculations, regardless of whether you delegate it to unity physics or do yourself. But both imply that you understand the physics behind how yoyo works.
btw something i would suggewt you to change is to make the holding a point on the line
change which point it is
so it doesnt infinitely stretch it
but that definitely has some usages as well
the holding point is on the line rn, but im not rly sure what you mean
it seems to just do nothing for some reason
no errors no logs no nothing
also, if you 'contract' the rope, and the point that you are holding onto gets deleted, you let go of it
try something lik
for(int i=0;i<PlayerList.transform.childcount;i++){
Debug.Log(PlayerList.transform.getChild(i).name);
}
the rope is made out of many different rope objects right
hm it seems like the previous one would also work, my guess is that there is actually something wront with your PlayerList, check it at runtime ro something
i would suggest to instead of like kind of holding on to a single point
(note this will be less performant)
to, first of all, limit the distance(through rb2D.addForce back to a connected point probably with force directly related to distance or something like that) and to check which point is the closest to the mouse when dragging rather than have a point be permantently held
wait then thats very strange
they were added at the start
i considered that, but to be honest it seems really hard to implement
like in the scene itself
i cant fix this pls help
hmm then you might just have stretching, but honestly thats not bad either
fix what?
omnipath
try like idk adding a random componnt to the gameobject PlayerList and see if it adds to the same one
!vscode
@formal niche yea.. its not too bad but im gonna have to read the docs a lot to figure out how to get them connected with force
lemme try that
gl with your journey
also does rb2d.addForce work for 3d objects?
its a 3d rigidbody rn
then you cant use the 2D version of the scripts
although idk why you would
need to
most of them are the same
or similar
np
wait how should i check if it is added to the same one
just look at the object
im not really fond with the debugger yet
after inspector in runtime
yeah ig
i havent used the inspector in runtime yet where can i open that
wait huh
um
scrnshot
your unity
does it accout for what happens in build too?
pls help with my issue i intsaleed .net 7 also but its not working
um build should be the same
its not changing at all when i run a game build for some reason
ummm not my scope of expertise sry i dont really know how to help, but as a note, do you actually need to care about that window, does it interrupt with unity?
nope i a need autocomplte
the component is not getting added but like nothing thats happening in the game build is reflected in the inspector
the component does get added when i play it in the editor
runtime stuff reflects in the inspector
oh
you mean the build
is different
yep
its not showing basic code also like transfor
from the editor
this entire issue is only happening in the build
pcmaclinux standalone


