#archived-code-general
1 messages · Page 251 of 1
btw do you know what is layoutkind.explicit? (if you know that then you will understand why i am using this)
use string.SubString
tbh i dont understand at all all the first code block
and the link with the second one
i still need OnDrawGizmos
You can add them but the result is not string it's char
Basically like adding their ASCII values
Substring is what you want here for sure
Or use a StringBuilder and Append them to it
you can have a queue of type IDraw, then when you dequeue in ondrawgizmos, the queue returns you and IDraw and you call IDraw in Ondrawgizmos
just command pattern
im a bit lost, i'll do some research around queuing and dequeuing
ty for the htlp
okay i understand
you can have a other data structure eg stack to do this, if you will process all the requirement at one ondrawgizmos call, you just need something to store all the commands before ondrawgizmos processes them, queue guarantees first in first out.
i create a empty queue,
then when doing my usual code, i add what i need inside the queue
inside OnDrawGizmos i dequeue all elements and do what is needed
ty for the help, i really appreciate it
i just got one question, i cant find the proper sythax to init a queue, all i found is this line of code in a old post
private var textQueue = new Queue.<int>();
but in VS i get a synthax error
the .
not quite sure if string.Concat(ReadOnlySpan<char>), available in NS 2.1, if it is available, use that instead of Substring and you'll get almost zero alloc
string test = "QWERTYUIWERTYU";
string fastString = string.Concat(test.AsSpan(10), "- DoDoDo -", test.AsSpan(0, 5));
pretty neat
how can i queue the method, and not the return value ?
for know i got this
public interface IDrawCustom
{
void DrawSphere(Vector3 position, Color color);
}
public class LevelGenerationManager : MonoBehaviour, IDrawCustom
{
public void DrawSphere(Vector3 position, Color color)
{
Gizmos.color = color;
Gizmos.DrawSphere(position, _sphereSize);
}
Queue<IDrawCustom> _drawingQueue = new Queue<IDrawCustom>();
_drawingQueue.Enqueue(DrawSphere(_startPoint, Color.green)); // error because cant convert "void" to "IDrawCustom"
Enqueue(this)
what do you mean by this ?
It's the object that implements the interface that you enqueue
Not the method
To enqueue a method you would need to have a queue of delegates
i still cant make it work with delegate
i get some types conversion error
how do you do a delegate with params ?
public interface IDrawCustom
{
Vector3 position { get; set; }
Color color { get; set; }
void DrawSphere();
}
...
Vector3 position {get; set; }
Color color { get; set; }
public class LevelGenerationManager : MonoBehaviour, IDrawCustom
{
public void DrawSphere(Vector3 position, Color color)
{
Gizmos.color = color;
Gizmos.DrawSphere(position, _sphereSize);
}
Queue<IDrawCustom> _drawingQueue = new Queue<IDrawCustom>();
position = _startPoint;
color = Color.green;
_drawingQueue.Enqueue(this);
okay so instead of having position and color as params you set them as properties of the interface (and so class)
I'm using a ruleTile that has tiles set in a TileBase
code:
var t = oreTable.GetRandomItem();
if (t.id == 0)
groundTileMap.SetTile(new Vector3Int(x, y, 0), groundTile);
else
groundTileMap.SetTile(new Vector3Int(x, y, 0), t.tile);
}
As you can see the auto tile rule doesn't understand there's a tile a single tile not part of its tilebase at a neighboring coordinate.
a) is there a way to have the ruleTile adjust if it finds any tile is found (aka not one part of the ruleTile rules?
b) is there a way to have some tiles in the ruleTile [let's say either in the TileBase or perhaps palette - these two terms might not be accurate] that aren't involved in the actual rule. e.g. i'm 99% sure that the following code wouldn't work but something like this:
groundTileMap.SetTile(new Vector3Int(x, y, 0), groundTile TinOreTile);
Thanks!
exactly
how am i suppose to dequeue to execute drawsphere ?
doing _drawingQueue.Dequeue(); doesnt do anthing
It gives you the object back
so i save it and exec ?
Then you can call DrawSphere on it
IDrawCustom custom = _drawingQueue.Dequeue();
custom.DrawSphere();
okay ty
but is saving each time a instance of LevelGenerationManager a good idea ?
because this will runtime the entir game
it's just a reference to it not the whole thing
okay so it doesnt load all vars, etc ?
no
man you need to learn some basic C#
there is always something to learn, i cant learn all then go write
i prefer taking a wall a few times and the rest of the time enjoy writing code
but yes this looks pretty basic c#
cpp is much much harder than c#
the correct sequence is Think->Google->Read->Code->Ask
this is what i do
then I guess the 'Read' part could use some work
but sometimes articles, docs or forums text and examples are not understandable for me, so i have to go test coding or ask here for different/detailed explaination
i do my best, i try to not ask in here
actually cpp is much easier than C#, less library crap to deal with, getting it not to crash, however, is another matter
it's actually amazing how hard it is to get C# to really crap out
is the draw of gizmo depending of the instance of a class ?
the drawn spehere is cleared after half a sec
Hi Pals,
I'm a beginner with some experience in coding. I would like to know what's the best way to create a simple 2D board game like Rummikub with draggin cards feature and having a board which allow to placement from the player hand board the cards?
there is a lot of steps to that tbh. i think that is way beyond the scope of a simple discord message
you’d need to define the board, the hand, the pieces, and movement. For each, you need the representation of a data structure, logic to do what needs to be done, and the graphics.
hello, I wanted to create feature to type to cheat similar to how GTA san andreas done it. By pressing a sequence of letters.
What would be the best way to do it? The only thing I can come up with is by doing Input.GetKeyDown for every single buttons. But that doesn't sound very nice. What would be more sophisticated method?
you're gonna have to capture the Input data however you do it but a FSM is the optimal way of dealing with that
I think I can do the sequence. What I'm not sure how to do is reading the input.
I haven't used this myself, but I believe that's what this is for:
https://docs.unity3d.com/ScriptReference/Input-inputString.html
hmm... very well then. I guess I have no other choice.
I did plan on doing that. But looping array every frame just for a cheating feature made me feel dirty.
Or do i not have to do that every frame?!
hi can someone help me with this script? in this script i basically have an input field which i can type phone numbers in it (and i can configure the numbers in the inspector) the problem is, no matter what number i type it gives me the invalid number audioclip. i also setted up a debug log to tell me which number i typed and it always appear to be blank. sorry for my bad english. can someone explain me this? thanks in advance
i have no idea what the language is(i guess the meaning throughout the script)
are you serializing the argument in inspector and the value is ""?
its italian sorry
what do you mean?
public void AggiornaNumeroInComposizione(string nuovoNumero)
```are you setting this function to be listener of some event in inspector?
it should basically read the numbers i created in the inspector and if the number is valid it plays the audioclip of the number i compiled if the number is invalid then in plays the invalid number audioclip. the problem is it always plays the invalid audio clip even if the number is actually valid and listed in the inspector.
like this
the Segreteria Audio means the invalid number audio
no, i am asking you is this function are some eventlistener eg onendedit,, sounds like you set some function with string parameter to be eventlistener and the parameter is serialized, then the inspector passes a empty string when the function is called
i have the multi-instanced class "foo" that registers/deregisters the given instance to a certain registry. This is done in OnEnable/OnDisable magic methods.
I have class "bar" that instantiates "foos", and then initializes the foos.
My goal is that "bar" can initialize data within each foos prior to the OnEnable call.
Right now, bar has the instantiation call followed by the initialization call. However, OnEnable in the foo class is called before the initialization. So it registers itself but it registers itself with the wrong data.
Can I somehow fix this whilst preserving registration in OnEnable?
If you're instantiating a prefab, you can disable the prefab before instantiating it. This will spawn a disabled instance where OnEnable won't be called until you enable it again. Just note that it will change the prefab asset and be serialized unless you revert it.
Another option to avoid the prefab modification is to spawn it under a parent which is disabled. That achieves the same thing.
Well, every single prefab I instantiate is subject to the initialization requirement. If I can use the same solution across the board, this is good enough for me. This will solve my issue, thank you.
Architecture question here - I'm using a species scriptable object to store data for each of the different species of creature in my game. Data range from things like which meshes and textures the creature uses, through to stats such as the character controller's maximum acceleration and speed. Some species are sexually monomorphic, whereas others are dimorphic. I'm currently using inheritance to solve this; a 'SpeciesType' scriptable object instance might hypothetically be something like a deer, a tortoise, a humming bird or a banana slug, and would contain nested classes like 'MeshData' and 'StatBlock', so I've made a 'DimorphicSpeciesType' that extends SpeciesType and overrides each accessor for constituent data with one that looks through two fields instead of one, and then returns the correct one based on the individual character's sex, which is provided using dependency injection. This works, but my problem is that there's a huge amount of waste here (mostly in terms of wasting my time), particularly with regards to setting up a new species. For example, suppose I create a new instance for a mallard duck, where sexes are visually distinct, behaviourally a little distinct, but in most statistics are functionally the same - putting two sets of data into the first two categories makes sense, but then is just doubling up on pointless data entry for the stats as I'd just end up writing the same number twice over and over again (increasing likelihood of making an error and making me very bored). I could obviously split each of the nested classes into scriptable objects themselves which use the same inheritance trick, but then I have a project full of a bazillion scriptable object instances. I could go further by using an extendable scriptable object for each individual datum, kinda like a static variable I can pass around, but having a project with literally tens of thousands of instances of those, sounds like the same nightmare but worse. Is there a better option?
is there an alternative or suggestion on this issue?
I'm not sure if what I'm looking to do is more involved and I need to use Unity's Custom Rule Tile Scripts or not.
It sounds to me like you shouldn't have specific classes for every possible way that something could be di/tri/etc.-morphic
Think of it more like a query filter.
consider the duck case
you'll have two sets of attributes for male ducks and female ducks
Each should have a "filter" associated with it that determines if it's relevant
You pass in a big blob of qualities your creature has
and the filter returns true if every quality it cares about matches
I can see one major problem here: it'd be possible to have a list of blocks that isn't complete
e.g. if you only included the female duck attributes, then you'd have a problem if you plugged in a male duck
none of the attribute sets would match
You could try to prove that you cover all cases (this sounds hard), or you could just fall back to a default choice and log a warning.
Once you have many attributes, you could also make things fuzzier than "it all matches" or "something didn't match"
like picking the attribute set with the highest score, where you get a high score when your qualities are good matches with the filter
Hey guys !
Im having troubles trying to do the first commit of a Unity project because it has large files, anyone able to do a quick voice chat for me to show the issue? i have tried to install the LFS as well 🫡
people aren't going to join a voice chat. but they will have the answer for you!
You probably don't have a .gitignore in your project
so Git is trying to commit everything in your project, including stuff like the Library folder
which is stuffed to the gills with cached files
uh oh, github threw a 500 at me
there we go.
You will want to have this in the root of your project. It'll make Git ignore everything that doesn't need to be tracked
(rename it to .gitignore)
for some reason these scripts are causing a problem that should not be occurring and i don't know why
// in other script
public void CorrectColliders()
{
foreach(Collider2D col in colliders)
{
HeightCollider colHeight = col.GetComponent<HeightCollider>();
colHeight.dynamicColliderHeightLevel = colHeight.startingColliderHeightLevel + (int)entityHeight;
if(colHeight.startingColliderHeightLevel + (int)entityHeight == 0)
{
Debug.Log("something went wrong");
}
colHeight.ChangeHeightLevel();
}
}
// in HeightCollider script mentioned above
public void ChangeHeightLevel()
{
HeightManager.heightManager.levels[currentColliderHeightLevel].Remove(col);
HeightManager.heightManager.levels[dynamicColliderHeightLevel].Add(col);
currentColliderHeightLevel = dynamicColliderHeightLevel;
}
The CorrectColliders() function is called in the update method, and as you can see in the if statement that has the debug, it's checking if some variables add up to 0. I'm debugging this because for some reason, the colliders are being added to list 0 when they shouldn't be, for seemingly no reason. I can get if this could be confusing; there is a lot of stuff going on here.
need a bit of help
Hi everyone, i'm stucked by problem that i can't find exactly how to solve. Im using service locator pattern. And i need every service to be registered at OnEnable and unregistered at OnDisable. I don't want to write it everytime just the same code. My static ServiceLocator class uses generic T where T : IService and actualy it's our service object. Now here is the question, can i make an abstract class or another component which will be registering this services, and for which one i actually won't need to write code for specific service but just for any component that i inherrit from IService?
Spescifing the question:
I see two ways to solve it, both with questions:
- Creating component that will register any kind of IService, the question here is how to make GetComponent<IService> returning class inherited from IService (as generic).
- Change IService to a class, where will be OnEnable and OnDisable methods and register them in that class, then inherrit any service from that class, th eproblem is how to get the type of the class there.
Where do you set up levels?
I wonder if you've put the same object into it multiple times
levels is in a script called HeightManager
i don't think that's part of the problem though, it doesn't change what's in the levels
but you said things are being added to levels[0] even though dynamicColliderHeightLevel is non-zero, right?
yes
important thing to note this only happens when i'm "jumping" and also on a platform at the same time
you might need the code for that stuff too
is this for platforms you can jump through from below?
ah, I see
I don't understand this.
isn't it changing what's in the levels incorrectly?
(If this was the case, you'd see the same object appear in two or more lists simultaneously, because two or more things in levels are literally the same list object)
no the thing that changes which level stuff is in the object itself, in this case it's a function called CorrectColliders
and it also doesn't appear in 2 lists simultaneously it's just the wrong list, the list it's supposed to be in is empty
if(colHeight.startingColliderHeightLevel + (int)entityHeight == 0)
were you intending to log something different from
colHeight.dynamicColliderHeightLevel = colHeight.startingColliderHeightLevel + (int)entityHeight;
oh wait, I misread
it's a bit hard to parse :p
Make sure you don't have "collapse" turned on in your console, by the way
Usually abstract class would be used here. You can do the first option by default, you can grab interfaces and it will work as expected.
Hey Ho! I have 2 types of Projectiles, one that shoots at a direction and one that shoots towards a position and acts once it gets there, from there on out many more types come out (For example a sniper as normal projectile and a rocket as targeted projectile) I have thought about using abstract classes, but the only thing the projectiles have in common are that they come from an owner and do an action once interacted with. Maybe interfaces work better with this but I am just unsure, would appreciate it if any of you could help me on this!
that would make it seem like only one thing ever logs
I see no reason for this to put objects in the wrong list
i've discovered that it only does this if i'm jumping as i said before
and if the player's floor height, (basically where gravity stops) is above zero
i can show you the code for that stuff if it might help
have you checked for this?
yeah but it's not causing any errors or stuff
Your problem is that you're seeing things added to levels[0] when you think they shouldn't be added to levels[0]
if you mean by the first option GetComponent<IService>, then it's actually doesn't, it'll register exactly IService, not the class inherrited from IService
also the debug thing doesn't seem to find it, but the colliders are still being added to level 0
Which is why you have that log statement -- to check if the value is actually 0
yeah
do you have info messages hidden?
no
then something else is calling ChangeHeightLevel() or something else is manipulating the list
I would suggest logging in ChangeHeightLevel instead of in the thing that calls it
or attaching a debugger to find out exactly who is responsible
this one is my service locator
I dont know what you mean by that, it gets you the object implementing IService. If this isnt what you need, then you're likely using interfaces wrong
ok I'll try this and get back ty
this is exactly the same code you posted yesterday, it would appear you have done nothing to debug the problem yourself
This one is simple Service inherited from IService interface that actually is an empty interface
Using an interface or abstract class here would help with whatever is launching these projectiles, although you maybe dont even need it. If nothing is specifically gonna store IProjectile or whatever you call it, theres no point
I cant read these on mobile !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.
in general, if you want to prove to yourself that condition X holds when Y happens, you must do that as close as possible to Y
otherwise you're only proving that it holds in some circumstances
I want to make code from region IService to be uniform for any kind of service and don't write specific ServiceLocator.RegisterService() and unregister respectively every time i creating new service, so i want to implement it in an abstract class that will be in the place of IService or in component that will be the same for any service monobehaviour and will make registration part.
for some reason when i added this debug if statement to this function it gave an nre?
public void ChangeHeightLevel()
{
HeightManager.heightManager.levels[currentColliderHeightLevel].Remove(col);
if(dynamicColliderHeightLevel == 0)
{
Debug.Log("something went wrong");
return;
}
HeightManager.heightManager.levels[dynamicColliderHeightLevel].Add(col);
currentColliderHeightLevel = dynamicColliderHeightLevel;
}
it doesn't do this if it isn't there
on what line?
on the 3rd line
if(dynamicColliderHeightLevel == 0) ?
where it tries to remove the collider
i'm going to remove the return because that shouldn't change anything from how it was before
Perhaps that's because it returns early and doesn't set currentColliderHeightLevel
and see what comes up
well currentColliderHeightLevel is set in the Start method of this script
which is really confusing
Perhaps you were calling ChangeHeightLevel once before Start ran
It's hard to say anything without understanding all of the moving parts here, and the order they run in
nvm
that's weird
it's not throwing the nre anymore
well it still apparently is never 0
i debugged the actual value of dynamicColliderHeightLevel and it was only ever equal to 0 when it was supposed to
not really sure if this is still a question anymore, sounds like you know what to do. As I said above, abstract classes is probably nicer to use here. It just saves you from writing the same code, and if you need to override the functionality then you can.
A separate class would still work, but would likely be more tedious to customize
Yeah I need all projectiles specifically in 1 group so I think I'm going with an interface as an abstract class just doesn't seem the right thing to do here, thank you!
but how to get the object of class that inherits from that IService (or replacing abstract class) in this abstract class
You wouldnt use IService anymore, just the abstract class
Otherwise theres no use of the abstract class
You'd just trigger another projectile method when you'd collide and check if there's an additional projectile methods to instantiate
gotta be careful with a recursive design that you don't endless spawn them
yes Abstract class Service replaces IService and i need to get somehow this class specification in Service to register actual service to ServiceLocator, not depending on specification.
Depending on how you code it, you might not even need these tbh. The launching of the projectile can be the same code, then any other effects can exist as a separate script on the object
also those 2 projectile methods can be merged as one since a direction is simply two points much like your other method
I really dont know what you mean by this
for example i have
public class CrystalManager : MonoBehaviour, IService
{
public Action onAdd;
private int _crystalCount;
public int Crystals => _crystalCount;
#region IService
private void OnEnable()
{
ServiceLocator.RegisterService(this);
}
private void OnDisable()
{
ServiceLocator.UnregisterService<CrystalManager>();
}
#endregion
public void AddCrystals(int crystals)
{
_crystalCount += crystals;
onAdd?.Invoke();
}
}
i want to remove IService region from here
i want this region of code to be uniform for any kind of service
not depending on is it CrystalManager or something else
the implementation seems fine to me honestly
I dont see what the issue is, you can just directly make an abstract class and this will work as expected
won't it register abstract type, just the exact CrystalManager or smth else?
okay i'll try again, if i'll have issue i'll show it
Im confused on why you want a single IService interface the whole idea is to have a interface per service
man I suck at understanding what people try to do with generics since I question my own practices
what I'm not getting is why you care about type if you're storing them as a single interface implementation
you should just have method call implementations on the interface
it's used as generic
so i replaced IService with Service and here is it, for example at onDisable i'm unregistring Service not Crystal Manager or smth else specific
how can i get type of class that is inherrited from Service inside Service?
Its still gonna be generic if you have a ICrystalService that inherits IService
i not only need to get the type but also the whole specific object of class
Then you dont have to register the concrete class
but then what's the point, im already registering it for any specific service. The problem i see is that i can't undrestand how to register any kind of that IService uniformly, not writing it in specificWay for ICrystalService or CrystalManager or for any other specific Services
for example here I have the same code again
public class CardManager : MonoBehaviour, IService
{
public Transform cardRoot;
public GameObject player;
public Action onDeactivate;
private List<GameObject> _currentCards = new List<GameObject>();
#region IService
private void OnEnable()
{
ServiceLocator.RegisterService(this);
}
private void OnDisable()
{
ServiceLocator.UnregisterService<CardManager>();
StopAllCoroutines();
}
#endregion
i want to make registration uniformly not depending on service specification
Oh man i have no idea how a certain object is spawning
- i failed to find its prefab
- failed to find instantiation in code
is there any way to check?
don't want to rewrite region's IService code again and again
i wanna it to be just one time and it need to work for every Service that the idea
and i can't find how to do that
oh let me think about that
yeah may just need an abstract layer
that's generic itself
do you have any ideas how to implement that?
Yeah, let me think about it
public class ServiceHandler<T> : where T : ServiceBase
{
T Value { private set; get; }
private void OnEnable()
{
ServiceLocator.RegisterService(this);
}
private void OnDisable()
{
ServiceLocator.UnregisterService<T>();
}
}
public abstract class ServiceBase { }
public abstract class CrystalHandler : ServiceBase { }
public class Test
{
ServiceHandler<CrystalHandler> crystalHandler = new();
}
This is my idea without interfaces and using an abstract base, but it requires everything to inherit from ServiceHandler. Still not sure why you register by instance but Unregister by type.
Rather, you want to do one or the other, but I assume if it's a singleton you want to register and unregister by the instance
yes it has some simmilar with singletone but in more accurate way with ServiceLocator, also unregistering by instance is not a problem
many thanks, i'll try to implement something simmilar
probably another way I can think of with interfaces but that's with covariance and honestly way overkill
just have understood exactly what you did, looks pretty ineteresting
nevermind, i think with interfaces it'll be worse
the only thing i'm afraid, that how to implement <T> with Monobehaviour
Could you have not have use
public abstract class Service<T> : MonoBehavior where T : Service<T> {}
...
public class MyService: Service<MyService> {}
oooooooooooo, that something looks really as i need
thanks
Why do you need the type of class, even interfaces do not provide you with this.
Oh a lot has been said between when i last opened this, ignore me
Disable stuff until it stops spawning, or maybe just put a script on it with a runtime error so you know when it happens exactly
hi. does anyone know how to check for collisions while inside an Ienumerator?
an IEnumerator does whatever code between yields
You mean using Physics.Raycast() instead of something like OnCollisionEnter()?
that is a good solution :)
There are also sphere,box, and capsule casts if you need a shape instead of a ray
private Vector3 RandomPositionInBounds(Bounds bounds)
{
return new Vector3(
UnityEngine.Random.Range(bounds.min.x, bounds.max.x),
UnityEngine.Random.Range(bounds.min.y, bounds.max.y),
1
);
}
I am trying to figure out how to set this up.
Any ideas?
My bounds are -0.25 to 0.25 on X axis
Inspector:
https://i.gyazo.com/517de3d6d610992eb743671b0ca8859e.png
I am trying to create an Enemy spawner that spawns them at a random position inside this box.
Ignore me, the issue was that I was spawning from a wrong collider 😄
Is there a problem with it? you havent really stated any issues. Im unsure where you see the -0.25 and 0.25.
The transform scale also shouldnt be affecting the bounds if that's what you want
Darn just replied too late
I was worried that everything I do is broken lol, but luckily its always just my mistake ;]
unless you actually want a collider, you might want to just define the region, btw
I removed scale and simply resized the collider
I should try a region
Whats a region tho?
use a gizmo to draw the box
like, you just have a bounds or something that defines the area in space. and then you have a gizmo to show it when you are in editor
yes
rather, your code can display the contents of the fields of a monobehaviour as a gizmo
That seems complicated
depends on how much you use it
Is it better than just using a collider to get a box?
I made collider to be "isTrigger", I can even make it ignore collision with a 2d matrix
Tbh I cant find a good way of making a spawner like system, previously I used a camera bounds for it(I might do the same again)
camera.x + camera.width + 1
random(0, camera.height)
it’s lighter. a collider interacts with physics system. it has a whole lot of variables involved, and gets involved in physics queries until it gets filtered.
….or you just keep 2 vectors to represent a box. and display it in editor
does anyone have a clue why the raycast isnt shooting in the Jump function? i have no clue why but the input (so the "gets input" print) is triggering when it is supposed to but the raycast then doesnt always run for some reason.
!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.
this is the function if that helps better
If you simply just need areas for spawn points to exist, just have a script which stores some
[SerializeField] Bounds bounds;
Then draw it OnDrawGizmos so you can visualize it. I do this and also assign a weighting to each one so I can have weighted areas
please follow the bot's instructions for posting code instead of uploading it as a text file
like this?
Did you read the bot message?
yea dont get what u need to do i guess thats my problem srry
Look at the large code section
i feel like they are only reading part of each message and ignoring the rest considering i even pointed out the "instead of uploading it as a text file" so they go and upload it as a text file again
I think discord auto makes it a txt file when the text is long enough, but im on mobile so cant really see if that's the case
Doubt they were dragging it in as a file
it would be called message.txt if that were the case
k so i hope i am doing it good this time around srry i have never used the discord like this. so the problem is at line 126 where it doesnt trigger for some reason https://gdl.space/ukabosobax.cs
it will only print the "Shoots raycast" log if the raycast actually hit anything. if it doesn't hit anything then only "gets input" would be printed. of course your logs are fairly useless since they are not printing any useful info that would tell you why your raycast isn't hitting anything
you should also consider drawing the raycast with Debug.DrawRay so you can see where it actually is
i will try this tho i am pretty sure it does hit because i am standing on the ground everytime i hit the spacebar
if it hit something then it would log "Shoots raycast" since it isn't logging that then it isn't hitting anything
@upper pilot https://github.com/LoupAndSnoop/GenericDataStructures/blob/main/Bounds2 This might help you
Bounds2 is a 2D Bounds, and it has a method to draw a gizmo pertaining to the region
to use it, in your Monobehaviour, you need to define a function called OnDrawGizmosSelected() and use it there.
Hey Lloyd, just going back to this issue now. Excuse the delayed reply. Do you know how to disable signing from Unity, or remember how you've done it in the past?
i've had code signing problems when trying to do an IL2CPP build on macOS, but I don't think I've seen that exact one
has anyone used DialogNodeBasedSystem
i don't know how to put text from a variable into the text here
it uses TMPro if that helps
Youd probably have better luck asking the creator of the tool, or in their forums/discord if they have one.
i'll probably check that yeah
Assigning the text of a text mesh object is easy, but to assign a value to that node depends entirely on how the dev made it
though either way, in general is there a way to do that through TMPro? Like, something like "you have [Player.health] HP"
String interpolation, which is basically what you just wrote except uses {}
You would assign it to the .text of your text mesh thing
so like,just writing it there in the Text box?
No it would be via code
thing is, this is for a whole dialogue system
🤷♂️ if you want to include a variable inside your dialogue, you're gonna have to access the variable somehow.
You could probably do some reflection stuff to make it easier to setup in inspector, assuming TMPro doesnt have this
i should check on that
Any inspector versions though will suffer if you change the variable names, not really sure if theres a good workaround for that. I would say making a good system like this would require a decent amount of knowledge already
Maybe check if the tool you are using, or tmpro, has this feature already
issue is, the person who made the tool did basically no documentation
and by basically I mean literally just a 3 minute video
it's DialogNodeBasedSystem
open source or not?
yeah it is
yeah looks extremely straight forward
look at what SentenceNode is doing and extend it
This looks a tad barebones tho
There might be better options out there
yeah just grabbed a free one that had start/end of dialogue events
{
base.Draw(nodeStyle, lableStyle);
GUILayout.BeginArea(rect, nodeStyle);
EditorGUILayout.LabelField("Sentence Node", lableStyle);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField($"Name ", GUILayout.Width(lableFieldSpace));
sentence.characterName = EditorGUILayout.TextField(sentence.characterName, GUILayout.Width(textFieldWidth));
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField($"Text ", GUILayout.Width(lableFieldSpace));
sentence.text = EditorGUILayout.TextArea(sentence.text, GUILayout.Width(textFieldWidth), GUILayout.Height(textFieldHeight));
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField($"Sprite ", GUILayout.Width(lableFieldSpace));
sentence.characterSprite = (Sprite)EditorGUILayout.ObjectField(sentence.characterSprite,
typeof(Sprite), false, GUILayout.Width(textFieldWidth));
EditorGUILayout.EndHorizontal();
GUILayout.EndArea();
}```
here's the code for how it does the text
no, this is the code that creates the node
I was checking the asset and I think this is quite literally meant for just dialogues with no variables
do you have recommendations for ones that can use variables?
Has anyone used the Fish-net asset before? If so, what was your experience like with it? I've watched a ton of videos on it and having no max for CCU seems really interesting for a smaller scaled 2-4 player project.
I personally never had the need for one, but a cursory search found this that seems to be a lot more feature complete
https://github.com/merpheus-dev/NodeBasedDialogueSystem?tab=readme-ov-file
thanks, may try that
here it says that there's no release
no releases usually mean that the repo itself is the package
just download the repo as a zip
is it better to use unity nodes or to code every lines ?
use a mix
You mean visual scripting? If you can afford to learn coding, it's always preferable.
oh you mean visual scripting? visual scripting is for peasants
for the unwashed masses, if you will
*designers😬
that’s mean to designers, who are forced to use visual scripting against their will
no sane human being would look at a mess of nodes and say “yeah. this is better than just writing a script”
and sail off into the sunset
Visual scripting is really good for some things
you dont wanna handle your physics on there tho
I don't mean to offend any designers. I mean that it was the purpose of visual scripting in the first place afaik.
the closest thing is for shaders, where the programming language allowed for shaders is like a caveman language
Wether it serves that purpose well, is a different question.
“Ug no like if statements. loops confuse Ug.”
Visual scripting is extremely good for some workflows yeah
We made an entire puzzle system based on nodes that to us was at least in the order or 100 to 200 times faster than making those same puzzles be entirely pure-code driven
“Ug not have black black for variable. Ug wife connect Ug bone toys with glowy fire stick”
its not even a designers thing, visual scripting is coding
Graphics buffer make Ug coworker big mad
one question
is there any way I could make it to turn something like the value "Player.HP" into the code reading it as "Player.HP"
that library has exposed parameters
you should be able to just plug that in with a scriopt
it just gets so miserable so quickly
Counterpoint: No human wants to deal with a step based workflow that you gotta repeat 1000 times without some kind of visual workflow
I wasnt a fan of visual programming until we had to code 100 puzzles which extremely basic but yet well defined sequence of actions
a node approach made us able to attack each puzzle in less than a few minutes
Oh yeah, it works fantastically for more specific problems
I think it just falls apart if you’re trying to do general purpose programming
It’s great for DSLs
I hadn’t thought of that specific application before!
yeah it falls apart for a lot of things
it really shines for work based approaches
decision trees, sequences etc
for example, this is a basic puzzle in TS
ok so
tried this for a bit and never got this to work
unity didn't really recognize the packageg
so yeah kinda back to square one about finding a dialogue system that can read variables
oh thought the com. meant it was a package
thats just the namespace
and it even has a package.json
let me open an empty project and see if I can get it to work
@hoary mason works out of the box, 0 issues
just put it in your assets
it does and doesnt, you gotta do it yourself
but its fairly straightforward, the code is super clear
did you mean exposedproperties by this?
idk if that's really what I'm looking for but I guess it can sorta work?
since I'd have to write extra code for every variable I'd want to input
also it doesn't have any way to go from one node to another without it being a choice, which is just weird
if you are looking for a fully featured system that does all of this for you there are very good paid assets in the store
having a single script that handles exposed properties should be trivial to implement
I tried doing it like this in the first one I was using, but didn't really work
dialogNameText.text = name;
dialogText.text = text;
dialogText.text =$"{dialogText.text}";```
dialogText.text =$"{dialogText.text}"; is basically the same as doing dialogText.text = dialogText.text;
this also completely ignores the underlying problem
this system all it does is whenever it launches, it replaces every single variable in the blackboard by the value set in the blackboard
what you wanna do is, externally, replace the blackboard values with whatever variable value you wanna replace
you do that from the parser script
and need custom code to do it, its your job now to figure out how to exactly do that and to what extents
yeah this was for the previous one you said was too simple
@hoary mason I suggest dont do this, but you can use reflection as a quick hack
the sane solution to this problem is to use an interface or base class with virtual methods, then use these to retrieve the data
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Sirenix.OdinInspector;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using Subtegral.DialogueSystem.DataContainers;
using UnityEngine.Events;
namespace Subtegral.DialogueSystem.Runtime
{
public class DialogueParser : MonoBehaviour
{
[SerializeField] private DialogueContainer dialogue;
[SerializeField] private TextMeshProUGUI dialogueText;
[SerializeField] private Button choicePrefab;
[SerializeField] private Transform buttonContainer;
public SerializableDictionary<string, MonoBehaviour> testEvent;
private void Start()
{
var narrativeData = dialogue.NodeLinks.First(); //Entrypoint node
ProceedToNarrative(narrativeData.TargetNodeGUID);
}
private void ProceedToNarrative(string narrativeDataGUID)
{
var text = dialogue.DialogueNodeData.Find(x => x.NodeGUID == narrativeDataGUID).DialogueText;
var choices = dialogue.NodeLinks.Where(x => x.BaseNodeGUID == narrativeDataGUID);
dialogueText.text = ProcessProperties(text);
var buttons = buttonContainer.GetComponentsInChildren<Button>();
for (int i = 0; i < buttons.Length; i++)
{
Destroy(buttons[i].gameObject);
}
foreach (var choice in choices)
{
var button = Instantiate(choicePrefab, buttonContainer);
button.GetComponentInChildren<Text>().text = ProcessProperties(choice.PortName);
button.onClick.AddListener(() => ProceedToNarrative(choice.TargetNodeGUID));
}
}
private string ProcessProperties(string text)
{
foreach (var exposedProperty in dialogue.ExposedProperties)
{
//Get value from dictionary instead
var obj = testEvent[exposedProperty.PropertyName];
var val = obj.GetType().GetField(exposedProperty.PropertyName).GetValue(obj).ToString();
text = text.Replace($"[{exposedProperty.PropertyName}]", val);
}
return text;
}
}
}
just a quick proof of concept I used a dictionary of variable names and monobehaviors and retrieve the variable value with reflection, but as a I said dont do this its dirty af lol
Wont play any audio in game, its attached to an object with an audiosource and everything is dragged to where its supposed to be
and the function is also being called because the couroutine runs
is there a symbol that is defined only when the application is built? something like #if BUILD?
well, the problem is that UNITY_STANDALONE_WIN seems to be defined in the editor, not only in a build.
then use the UNITY_EDITOR one. you know you can invert them with !, right?
no I did not, I thought preprocessors aren't affected by operators
or is my AI giving me old outdated unity approaches
it is against server rules to get help with AI generated code. and no, that is most certainly not anywhere near the best way to get input for movement
it is against the server rules to go "copilot suggested this while I was typing, should I accept it?"
OK. I will make sure not to mention the word AI next time.
you should write a comment in your code to remind yourself not to
what is something near the best way to get input for movement
if that one is outdated
it's not outdated it's just bad
the new input system
it does not normalize the input so moving diagonally is faster than moving on one axis. and it checks each key individually instead of using something like GetAxisRaw
best way to get input for movement highly depends on the type of game tbh
yes
if you are just doing a local 1p game just make a singleton manager and poll for inputs there
I'm not asking about conceptual design, I just mean like what API is the recommended one
new input system, bit of a PITA in the ass to set up but its pretty decent
old input if you want something more straightforward but less versatile
external solutions like Rewired if you want high OOB compatibility and no pain to set up
pretty much all work
also keep in mind that the context of the question (which was now deleted) was about using Input.GetKey for each WASD
to be completely honest I can see some situations where that might work, but yeah 99% of the time you set up those as axis'es instead
yeah im just wanting to learn the recommend professional one
so ill watch a few videos on new input system
yeah safe bet
- How can i check whether the static batch utility combine method has actually worked or not?
Is there a way to find a constant position and rotation offsets between gameobjets in hierarchy?
Each of gameobjects in hierarchy has different position and rotation.
Parent2, Parent1 and Child have their own constant localPosition and localRotation, so they wont be changed in time.
Whereas Parent3's rotation and position changes each frame.
I'd like to find constant offset in position and rotation between Child and Parent3
Hierarchy:
That sounds like you don’t want hierarchy :p
They should be in hierarchy since its like hmm a drone lets say. He is the top parent where Camera is bottom child and its mounted with certain offset to drone center, but it wont move or rotate in its axises, but still should change its world position and rotation due to drone movement and rotation
Is there any reason you need this constant offset ? The setup you are describing is not quite making sense to me, I would need to understand the use case
Said constant offset only exists if the movement and rotation are both constant
I just wanted to kinda reflect reality. With these offsets I would be able to "move and rotate" bottom child in its coordinate system to achieve top parent's position and rotation
Hello! How can I have a 2D perlin noise that could 'transform' (I think it's called phasing) and loop around. I have this code now:
private void Update()
{
if (Input.GetKey(KeyCode.C) || updateEveryFrame)
{
UpdateColors();
}
if (selfAnimate) phase = Mathf.Repeat(Time.time, 1.0f);
}
void UpdateColors()
{
foreach (SpriteRenderer leaf in leaves)
{
leaf.color = leafColors.Evaluate(
noise.cnoise(new float3(leaf.transform.position.x, leaf.transform.position.y, phase))
);
}
}
But there's a noticeable snap when the phase value goes back to 0. I couldn't find anything online that would do this.
Why does this has OnAttackHit is null on WeaponHit but is not null on AttackEnd?
It's seem to be null when called from other class
public void WeaponHit(AttackDirection attackDirection)
{
//this prints "Hit UP OnAttackHIt == null? true
Debug.Log($"Hit {attackDirection} OnAttackHIt == null? {OnAttackHit == null}");
OnAttackHit?.Invoke(attackDirection);
}
void AttackEnd()
{
//this prints "Hit UP OnAttackHIt == null? false
Debug.Log($"Hit {direction} OnAttackHIt == null? {OnAttackHit == null}");
if(!weaponHit)
OnAttackMiss?.Invoke();
else
OnAttackHit?.Invoke(direction);
}
Both are located on the same class
It's probably assigned by the time the second method is called. Or they are called on 2 separate objects.
they are on the same object, and onattackhit is assigned from start
🤔 maybe because the weaponHit function get called from another Invoke?
How do you know they're on the same object? Can you print the object ID or something?
Wait, they are indeed different gameobject doh
Thanks for the insight @cosmic rain 👍
Yoo hackers and developers... does findobjectoftype find only in active scene or in all loaded scenes ?
i want to search active scene only (or a certain/specific scene)
All scenes. You can get the root game objects in the active scene with https://docs.unity3d.com/ScriptReference/SceneManagement.Scene.GetRootGameObjects.html and do GetComponentInChildren or a manual recursive search through them
someone here reported the opposite https://forum.unity.com/threads/findobjectoftype-in-any-scene.530280/
void FixedUpdate()
{
Vector3 angles = GetAnglesFromCurve();
Quaternion rotation = Quaternion.Euler(angles.x, angles.y, angles.z);
Quaternion lookRotation = Quaternion.LookRotation(rotation * Vector3.forward, Vector3.up);
transform.rotation = initialRotation * lookRotation;
HomingAbility();
Vector3 posChange = currentSpeed * Time.fixedDeltaTime * transform.forward;
transform.position += posChange;
}
void HomingAbility()
{
//Find Target via casting
Vector3 targetDirection = (newTarget.GameObject.transform.position - transform.position).normalized;
transform.rotation = Quaternion.Slerp(
transform.rotation,
Quaternion.LookRotation(targetDirection, Vector3.up),
Time.fixedDeltaTime * currentState.MovementData.LinearData.HomingData.RotationSpeed);
}```
So I've been updating some of my projectile logic, I've been mostly just using directions without touching rotations as the visualization is handled elsewhere. But since I've added a bunch of extra controller logic, I've felt like I needed to work more with the rotation. In this case I'm applying angles to the projectile (handled by a curve over time) and these angles are relative to the initial rotation and not world, so I need to plug in LookRotation into the process. It works fine for the most part, but since I've added those changes my minor methods now require changes such as my HomingAbility() method.
This method previously changed directions gradually, but now that I've changed it over to rotations I've opt to use Quaternion.Slerp. Unfortunately it doesn't seem to meld well with how I'm doing the previous rotational logic. It seems abit snappy, and overall incorrect; I'm not entirely sure what values I should be feeding it for it to meld with the rest of the rotational changes.
The thing too is that both of these methods change the rotations, which is ideal if I want to keep a consistent rotating effect on the projectile, while also slowly changing its direction towards a target.
Is there a way to ensure that saving/loading SO "instanceID" is kept the same between builds?
Is there anyone who knows about Photon Engine?
Or do we need to save SO index or ID from internal database of sorts
So we are saving by JsonUtility which saves whole object.
It saves instanceID I believe.
We will go with GUID route then.
We just need a reference to the SO
I dont think instance ID is consistent
Btw does the asset store SO serializer help with that?
its not
Its just automatically saved by JsonUtillity
so it breaks when we make a new build(even with no changes)
Have you used it before? Would that make save/load easier?
Meaning it would save SO without having to keep track of GUID
saving isn't hard. It's the systems you need to set up that makes it hard
Right
Is there anyone who knows about this error? I was trying to fix it but still I couldn't find any way to handle it
You haven’t shared the code that the error originates from… but you’re trying to access an object that doesn’t exist *anymore
i feel like i did a move that i would regret for the next month
It happens when you Destroy(gameobject) but still try to do something to it
Probably in Update
The object doesnt seem to be deleted instantly, so the next Update is called but the object is aready null.
At least from my experience
https://docs.unity3d.com/ScriptReference/Object.DestroyImmediate.html
This is not recommended tho
I am not sure why Destroy() causes this issue, but I had same problem :/
if you want to get a control state that ensures that "destroyed = no longer used", then add s = null; right after the destroy line
I guess that means
Destroy(gameobject);
gameobject = null;
Never did that, I just check for if (gameobject == null) return;
The object obj is destroyed immediately after the current Update loop
This means(based on execution order) that it will try to call 1 Update loop after we clicked a mouse, or Destroyed the object in an Update?
What if we do
void Update()
{
if(heath <= 0)
{
Destroy(gameObject);
return;
}
}
Would that fix the issue of the object being null?
I have no idea how to do that to be honest, I don't think it can be null
It's about Photon Engine
It's really complicated, my brain is burning at this point now. I can create a lobby but when I try to connect two players, its not working
also my code is not in English so it will be hard for u to understand it
what's the actual problem you are (or were) having?
Nobody can help with this little detail. Please at least click on the error to see the stack trace
In one of my older games I was destroying a bullet gameobject, but it was still trying to access it so I had to do null check in Update to prevent the error.
It might have been an isssue related to having a reference to it in another script
oh yeah, that's a common issue
I wish there were events you could subscribe to for things like destruction
Yeah, the way I solved it was to have a boolean "ToBeDestroyed" or something
- a null check to be safe.
the secret is to just not destroy anything
Does anyone know how sea of stars does its tree animations? To me that doesn't look like a spritesheet animation. https://youtu.be/oS7l_cAFdNM?si=mK096Z9m_qvTPTOY&t=201
Sea of Stars - Gameplay Walkthrough Part 1 (No Commentary)
Checking the full game out. It seems like a classic rpg and has some good mechanics. Gameplay is from the PC version and recorded at 4K 60FPS. Would like to do a full series with all missions and side stuff. Hope you guys enjoy!
►NOTE - Thanks to Tinsley PR for providing me the review ...
I linked the exact time there are trees
#archived-game-design
though it looks like a vertex shader
My bad on the place. For sure didn't think it was art tho lol
to answer the now-deleted question, consider Plane.Raycast (:
Hahaha yes thank you! I deleted it because I just learned about it and it seemed like a solution 🙂
!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
we can't see line numbers like this
29,29
📃 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.
line
you have no idea what you're talking about
next time post in #💻┃code-beginner
this is not how you post code..
did you read the bot message
no line numbers . how useful are these do you think?
its not working idk
like have to put // in evey line?
where in the Large Code section does it says that
show me , ill give you 100$
but i am sending in the same format
man if you cant even follow instructions how to post code properly, how do you expect to code anything
like realistically
so problem is in 29th line
https://gdl.space/yayonexehu.cs
and this is the refrence script
it learns!
learns what
nothing.
anyway
one of these is null
if(pathGrid.transformsInRange == playerScript.playerControler.hit.gameObject)
Debug.Log them or use breakpoints and find out which one
both points are giving error as they cant get refrence
Actually your error is not even NRE
pathgrid is missing transformsInRange
do you know what Local variables are ?
How can I approach best tinting a whole 3D model with a specific color via script? The models I use have a variety of materials and I dont want to override their color or replace the materials
hey guys, I'm trying to find the most optimal way to make my game multiplayer. According to what I've read so far, Netcode isn't efficient for competitive modes. Our game will have both PvE, and PvP. Does anyone have any suggestions? Thanks!
hey there.
{
_target -= this.transform.position;
float angle = -Vector2.SignedAngle(Vector2.right, _target);
angle = Mathf.Clamp(angle, minRotationAngle, maxRotationAngle);
this.transform.localEulerAngles = new Vector3(0, angle, 0);
}```
This code is on a turret. That is on a space ship. When the spaceship rotates. The turret misaligns. I can't figure out why. Any help?
This can be simplified down to
_target -= this.transform.position;
this.transform.right = _target;
Assuming the turret's cannon points right
You're using a world space direction to caculculate your rotation angle but then you're assigning the rotation in local space
you'll need to convert the target position to local space before doing this, or just do everything in world space
e.g.
Vector3 worldDirection = target - transform.position;
transform.right = worldDirection;```
Or if you want to use local space and clamp the maximum angle as you are doing then...
public void AimAtTarget(Vector3 _target)
{
// get target's position in our _parent's_ local space, which is what localEulerAngles is expressed in
Vector3 localTarget = transform.parent.InverseTransformPoint(_target);
float angle = -Vector2.SignedAngle(Vector2.right, localTarget);
angle = Mathf.Clamp(angle, minRotationAngle, maxRotationAngle);
this.transform.localEulerAngles = new Vector3(0, 0, angle);
}```
I tried it with inversetransformpoint before. All the turrets just freeze then. I tried you code. They also just freeze
and it chould be new Vector3(0,angle,0) because thats the rotation axis or am I missing something?
you sure you used my exact code? You had y axis rotation before?
why would the axis be the y axis?
isn't this a 2D game?
that doesn't make sense
unless you're doing something really weird
im doing something really weird
ok it's unclear what any of the orientations of your objects are then
makes it quite hard to write this code
what's the orientation of the main ship? And does the gameplay happen on the world X/Y axis or the X/Z axis or what?
Im not quite sure myself. Is it right oriented?
2d perspective
I think it's just the model having the turrets on thier y axis...
well your ship model is very weirdly oriented
It's +z axis seems to pointing.. "down"
from the 2d topdown perspective
down into the world
but... that's kind of ok
one problem is because of the ship's orientation that throws the turret all out of whack
Hm. I see. Ill try to untangle this. Maybe Ill figure something out then
I think you want something like this?
public void AimAtTarget(Vector3 _target)
{
// get target's position in our _parent's_ local space, which is what localEulerAngles is expressed in
Vector3 localTarget = transform.parent.InverseTransformPoint(_target);
float angle = -Vector2.SignedAngle(Vector2.right, localTarget);
angle = Mathf.Clamp(angle, minRotationAngle, maxRotationAngle);
Vector3 finalDirection = transform.parent.TransformDirection(new (0, 0, angle));
this.transform.rotation = Quaternion.LookRotation(finalDirection, -transform.parent.forward);
}```
Nah, sadly doesn't work. I was so fixated on the Math and all that. That I tried everything but looking at the model oriantation.
Ill do that first before making a script that just works on this one turret
Maybe im just stupid, but shouldn't the z axis point down in 2dUnity?
+Z points into the screen.
I made a new project... Z points... away from the screen. Am I missing something. I tend to miss the point quite often.
the screen points +Z
"into" the screen
well yes, into the screen
so that's correct for a 2D game
It's just weird for a 3D model
If you're using 2D physics it's a good idea to have it how you have it
So I did that Part right. That's something
I found the orientation problem. The empty-obj "GunArray1" & "GunArray2" have been rotated by 90 degrees on the x-axis instead the gfx of the turret itself
I'm so... Sleeeppy.... Ehhwww
Hey.
I'd like to draw Lines/Curves inside my Project (Runtime, not Editor. 2D WorldSpace).
Those don't need any interactability.
Wondering what the best approach would be?
Using the GL class?
- LineRenderer
- The Vectrosity asset
- The Shapes asset https://assetstore.unity.com/packages/tools/particles-effects/shapes-173167
- GL
Thank you!
Not sure but i think LineRenderer may be too much for that usecase and i don't want to have every Line/Curve be related to a Component, but i'll try to do it with GL for now and take a look at the Assets you mentioned!
I have an Asset that would probably be able to do what i want, but i'd like to have a solution that is tinkered towards my single usecase only without any additional code/data that's not 100% needed. 🙂
Shapes will make some really pretty...shapes (:
Hey Fen thank you for answering me yesterday i didn't noticed it sorry :/
So i did already try a variety of gitignores and still got the same error, im doing the git commands using git bash and i even try using git desktop.
you shouldn't need to try a "variety" of things
on the command line, do git reset to unstage all changes
make sure you've placed that specific .gitignore in the root of your project
run git add . to add all files
Now, it's possible that you have some gigantic assets in your project that are over the size limit, of course.
ill try
There are several problems here.
"Bomberman" is the root of your project.
You should create the repository in that folder
You created the repository in a parent folder
so none of the .gitignore's paths are going to line up
It wants to ignore ./Library, for example, but you have ./Bomberman/Library
Delete the .git directory in your current folder. Enter the project root and create a repository in there.
I believe the .gitignore should work if it's placed in the child directory like that
However, you've also already tracked those files
notice how these are changes not staged for commit
It doesn't matter that you now want to ignore those files
Once they're being tracked by Git, it doesn't matter if they're in the .gitignore
If you don't have any particularly important history in your repo, I'd just delete the .git folder and create a new repository in the correct folder.
they're not pushed yet
Deleting .git will completely remove all of Git's data
You can also just ignore it for the time being, if you want to be really cautious
Git looks for the first .git directory it finds in or above your current directory
so once you create a repo in "Bomberman", it won't matter that you have a repo rooted in "BombermanAI"
Once you set up the new repo, you'll just need to add a remote -- the repository on GitHub, or wherever you're hosting this
here is an example using a Microsoft repository
git remote add origin https://github.com/microsoft/Guan.git
you'd replace that URL with the one for your repository
If you have code in the remote repository already, you'll need to force-push to overwrite it with the new commits
Okay, that looks good
git push --set-upstream origin main --force
--set-upstream will inform Git where you want to push your local commits to by default
You will still need to force-push
oh ok ill do it
basically, you've created an entirely different history by creating a whole new repository
git push --set-upstream origin main --force
this one right?
Right.
Also, if you want to use LFS, you need to set that up here.
before you commit these files
is it easy to make/see a codemap in visual studio?
i’m kind of terrified to see my spaghetti of dependencies, but I think it will be good for me
I don't use LFS very much, so I can't help you out there.
You definitely want to do that before you commit anything. Otherwise, you'll have the giant files in the repo anyway
Only in the Enterprise edition, as far as I know
At least for Microsoft's solution.
i see, and I have VS for Mac
the visual studio we have at home
Nice now i need to make the pull request to maIN?
did you set the upstream to origin/master instead of origin/main ?
yes haahah
just set it again and push
If you want them to match:
git branch -m master main
git push --set-upstream origin main --force
this will rename your local branch, then set its upstream to origin/main
no prob :p
I forget how you'd clean up the unused remote branch
but that's less important
Also, if you are using LFS, make sure that's working on GitHub's side.
i work with git for 7 years counting as software engineer ahaha but i never tried to setup a git after doing that much xD i've done the whole game prototype and then i remember that i may do some sh17 xD and GIT would be nice
You also use the "main" branch to put the working code and the "master" branch to put the latest release version?
damn right 😉
I haven't actually done "git flow" in a while
Simple can you check dm pls
Sure !
If I make a delegate as:
myDelegate += MyStaticClass.MyFunction;
...
myDelegate -= MyStaticClass.MyFunction;
Will this work normally or not?
i have only ever tried subtracting methods of instances from delegates
I would expect it to. MyFunction is a specific object.
Subtracting anonymous functions doesn't make sense because it has nothing to do with the one you subscribed
thanks
Hello I need some help on an error. I have a file with the name HeightMapMeshgeneratorSolid.cs
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UIElements;
using UnityEditor;
using TMPro;
//using System.Diagnostics;
using Utils;
public struct MetaFileData
{
public float scaleFactorM;
public int maxElevM;
public int minElevM;
public int renderMultiplierM;
}
public class HeightMapMeshgeneratorSolid : MonoBehaviour{
// code I won't show because it is too long and also not relevant
}```
Now for some reason I am getting an error (8 of them actually? as you can see in the scrnst) "'MetaFileData' is missing the class attribute 'ExtensionOfNativeClass'!". This doesn't even make sense because MetaFileData is a struct and not a class, and none of the forum posts I have seen about this error are about a struct having this error. I asked chatgpt and it thinks it is a bug...
Anyways thanks in advance if anyone is able to help me.
Also this warning on the component, which I have seen in forum posts talking about a CLASS having this error..
Im trying to set up animations but it always says the Parameters dont exist.
Can anyone help me to fix that?
It's right, there's no isPatroling here, and in your animator IsChasing has an uppercase I (in the code you refer to it with a lowercase i). Like most of Unity, names are case-sensitive, so the two names you have here are considered different.
i just installed unity 2019.4 and it is not opening on windows 7 What should i do?
#💻┃unity-talk because this is a code channel.
but you probably need to check the !logs to see if there are any issues
I need a little help from an architecture perspective.
List<Vector2Int> coordinatesToClear = MapSearch.GetAffectedRegion(map, (Vector2Int)target, objBase);
// Log for Undo/Redo
if (map != previewMap) {
List<TilePlacementInstance> objToDelete = MapSearch.FindAllBuildObjInRegion(map, coordinatesToClear);
foreach (TilePlacementInstance inst in objToDelete) {
buildHistory.LogPriorTileToHistory(inst);
OnTileInstanceRemoved?.Invoke(inst);
}
}
foreach (Vector2Int pos in coordinatesToClear) {
map.SetTile(new Vector3Int(pos.x, pos.y, target.z), null);
tileDirectory.TrySetRotation(map, pos, Rotation.E);
}
if (map != previewMap) OnMapChange?.Invoke(coordinatesToClear);
}```
I have a few methods that I want to refactor.
What these methods do is:
- Figure out region in tilemap,
- conditionally log/report that region
- Do something on that region
- conditionally log/report after the change
I want to split these methods up in a refactor, and it makes sense to split into a method that logs, and one that does not, so I can decouple the reporting code from the "doing" code
that's all well and good, but then I want to avoid code repetition when some of these such methods call each other
I'm thinking about making overloads with out parameters, where the out param method actually does stuff to out the inner regions we find during calculation
but the issue is avoiding repetition
example:
Do something
EraseAndLog(out y);
Do Something that also makes x
out x
}
void DrawAndDontLog() {
Do something
EraseAndDontLog();
Do Something that also makes x
}```
any advice?
can some one tell my why this happens when the animation finishes
probably an issue with your #🏃┃animation
i got it off of mixamo
That's the "no animation" pose.
You probably transition to a state that has no motion(animation) assigned.
Hello can somone help me with translate my app?
im trnaslate from this video:
https://www.youtube.com/watch?v=yvpPUTkQFM8
And static translate works perfect but problem is when i generete random monsters name... like on video
And i have no idea how tranlete words that were drawn using a script
Anyone can help me with that?
in this video you're going to learn how to make your game (Unity) multi-languages and without writing any code, just add a Unity package and some text ..done 😊.
CODE & PACKAGE
https://github.com/herbou/Unituts__MultiLangGame_Unity
❤Support Us :
☞Paypal :https://paypal.me/hamzaherbou
☞Patreon...
Hey I just have a general question. Are raycasts performance heavy or not? I found muiltiple different answers on the internet so I'm not sure.
no, not really. but if you are experiencing performance issues (or just worried about them) you should use the profiler to determine what is taking up the most resources
Alright thanks
Sorry if this is the wrong channel for it, but I'm having problems with VSCode completely ignoring my .editorconfig. I feel like I'm going round in circles trying to get it setup.
Any suggestions why it's being ignored?
I have the c#, c# dev kit, and unity plugins. I have used npm to install the editorconfig package. I have set [csharp]": { "editor.defaultFormatter": "ms-dotnettools.csharp"}
Sometimes it will work briefly, but then won't work for other files and I'm really not sure what the problem is :\ Any help much appreciated
Hey Guys 👋
im trying to make a pickup system but am having some difficulty
here is what i have so far
the current issue im having is i can pickup and drop items just fine
i just cant use them
basically i want to pick them up and for example for grapple assign a camera and player transform so that grapple can be used by the player who picked it up
and so that when they drop it, these got assigned to null so that when another player picks it up they can use it
much appreciated guys
!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.
I'm making a content loading system, but not sure how to properly organize it.
Imagine a generic item class, like "potion", or something and a class that takes care of loading JSON definition of individual potions.
JSON definition contains things like name, price, effects applied on use, gameobject prefab for visuals, etc.
The reason I'm going with JSONs and not SO or prefabs is because I want to be able to add content without relying on the editor.
Just wanted to clarify: My best course of action is to have all those defs loaded on start and cached (in a dictionary with an id key perhaps), then just construct a class on demand (since c# doesn't allow object deep-copying afaik)?
Sounds like you've got a plan.
More like a rough idea, but I'm going to try it when I get to my home pc and see how it goes.
Also, any potential issues with using a static class to load and hold all of those defs?
I don't see an issue. Maybe make it statically accessible instead of making the whole thing static though.
Good call, tnx.
Im using srp at the moment, how do i use the camera as an input texture and assign the output to a different texture?
SRP or BiRP?
SRP means URP/HDRP
Old one
Hello, does anyone know how i can load a scene in background like the async function but let be „loaded“ when i set a bool of it true
Like in the scene i want to load in the background i want to start a function and just when this is finish it should be set the Bool and then the async function should let it be loaded
But uh, chatgpt got my hand anyway
But can i start a function in that like in the bsckground it is altesdy loaded and i start a function in there from the start function until its finished
While i am still in the scene from before?
you would need to run the method in a DDOL object
unless you are loading additively
Additively kinda matches but i would like to make it Not seen by the player while i do somethin in the new scene until i say it tho
'kinda' either you are loading scenes additively or you are not
how can i change velocity of gravity without increasing gravity?
like i want to do low gravity then increase it overtime if im in air
calculate your own gravity factor then apply it to your velocity
Is it possible to get some unity features to work at runtime? I kind of need an FBX exporter. Trying to use "using UnityEditor.Formats.Fbx.Exporter;"
Just plainly downloading it and putting it in the asset folder has too many conflicts, but that's bound to happen 😂
UnityEditor namespace will never work at runtime so if you need UnityEditor features you will need to write your own equivalents
I would Like to but then i think the scene are over each other but i want the other scene to already do the start() function but Not be seen … 🙈
running code and not being seen means disabling any renderers
Ahh ok thank you, figured as much. It's a shame they never updated the FBX exporter to work outside of Unity
I recommend to use gltf for runtime exporting rather than fbx https://docs.unity3d.com/Packages/com.unity.cloud.gltfast@5.2/manual/index.html
Wow thank you! Will check this out
I think you need the newer 6.0 version and not the one I linked
Any idea why i get this error exclusively on build?
Kernel 'Main' not found
When trying to find this Main kernel
Is this call that throws the error:
m_InstantiatedComputeShader.FindKernel("Main");
Sounds like the shader isn't making it into the build.
I know that regular shaders sometimes need to be forcibly included
I haven't used compute shaders before, though. I don't know if the same thing can be done with them.
i have
#pragma kernel Main
on the compute shader
Unity doesn't include assets that aren't in use in some form or another in the project, but it can't know if you're loading something from code without ever attaching it to anything.
Either set this shader to be included in the Graphics settings (yes, even for compute shaders, they're still shader files and this only cares about the file type) or put it in a Resources folder that is always included in the build (and access it in code via Resources.Load)
I don't see anything that suggests they are looking for the shader at runtime. m_InstantiatedComputeShader is the ComputeShader instance, we don't see how they got it.
It seems to work great, still figuring out how to run it via script. I need to reference the assemblies, but for some reason textmeshpro gets errors 🙂
Anyone who knows why this happens? Only when I reference glt, TMP gets errors
an Assembly Definition Reference asset is used to add a folder to an existing Assembly Definition
once you do that, scripts in that directory (or any subdirectories) can only see assemblies that are visible to the assembly definition (because they're part of that assembly now!)
Are you trying to make glTFast visible to an existing assembly definition? If so, you need to add it to the "Assembly Definition References" list on that assembly definition
(yes, the names collide, and it sucks)
Yeah, that's what they mentioned. Import the package, then "Note: The GLTFast.Export namespace can only be used if you reference both glTFast and glTFast.Export Assemblies in your Assembly Definition."
I have never done this, so I just figured it would be right click, create assembly definition reference in the asset folder
Then you need to add both of those assemblies to the Assembly Definition References list of your assembly definition
If you aren't using an asmdef, you can ignore that
🤔
All assemblies are auto-referenced by the default "Assembly-CSharp.dll" assembly that all of your code is put into
I can't reference it in script unless I do add it as a reference manually. Need to read up on this topic, bit vague
Ah, perhaps they unticked "Auto Referenced" on their assembly definitions...?
let me look
where is this in the docs?
found it
also, if you have not used assembly definitions before, you can read about them here: https://docs.unity3d.com/Manual/ScriptCompilationAssemblyDefinitionFiles.html
They do have an assembly reference in the package, but for some reason the scripts can't find it
Looks fine to me. I can see the namespace after installing the package.
You may just be having an IDE problem.
Weird 🤔
In short: an assembly is a collection of scripts that are compiled as a single unit. The default behavior of Unity is to shove everything into one enormous assembly.
Assembly Definitions let you create an assembly out of the scripts in a folder. This cuts down on compilation times, since you don't have to recompile an assembly if nothing has changed.
Assembly Definition References let you put several folders into one assembly. They are only used to extend an existing assembly's scope.
Assembly definitions must explicitly list the assemblies they depend on. However, by default, they're also automatically referenced by the default assemblies, like Assembly-CSharp.dll.
Note: The GLTFast.Export namespace can only be used if you reference both glTFast and glTFast.Export Assemblies in your Assembly Definition.
This is only relevant if you have created assembly definitions. It's just a heads-up that there are two assemblies you need.
It must be some other issue, its a bit weird. Tried the regenerate project files
Have you successfully compiled since you installed the package?
None I didn't put in myself. There are quite a lot of them in the project, but most are generated by unity
you said you "referenced glt"
Unity does not automatically generate Asm defs for user code
Yo! Is using "RequireComponent" a good practice? What I was doing until now is sending a LogError if my component was missing. But "RequireComponent" do the same thing with less work right?
I find it mildly annoying when I'm trying to remove components from an object
since I have to do it in the correct order or I get blocked with a popup
I should try it and see if I find it useful or not. But there isn't any downfall from using it?
I always like to do it with MVC patterns, requirecomponent of type X
it's good practice if you have scripts that rely on certain components being there
👽 What is MVC patterns?
Ok that's what I needed to know. Thanks!
A style of coding, where you have separate scripts managing visuals and data
model-view-controller
Ok thanks, I will look at that
Quite a lot of them
that is not your 'user code' though is it?
True 🤔
I am confused by this message.
They just showed when I looked for the file type in file explorer
I'm talking about that specific asset you showed us earlier.
you said that, when you "referenced glt", you started getting errors
this implies you did something
So I imported the package with the + icon in the package manager
Tried to use using GLTFast.Export; the same in the example script
Didn't work
Then I read I have to reference the assemblies, so I right click the assets folder, create NewAssemblyReference
Referenced GLTFast.Export and then TMP didn't work
Delete that assembly definition reference asset. It is bogus.
I deleted it, there is no other one
Okay, good.
But still I can't call the using GLTFast.Export;
Did you also close your code editor, then reopen it after regenerating the files?
Yeah, restarted my pc even
It may not pick up on the new .csproj files until after it restarts.
Oh, one other thing
Make sure you've successfully compiled after removing the asmdef reference asset
Although I'd expect you to be having a ton of other problems if that was still lingering
I can run the project and I can create builds
Okay, so that's good.
One last thing to sanity-check -- if you add using GLTFast.Export;, do you get a compile error in Unity?
from the menucontext, i am running a function that builds a dictionnary, how can I make this dictionnary save so it doesnt get destroyed at the next domain reload ?
ik its about serialization, but I cant find the correct attribute
in Unity, not in the code editor, right?
Can you show me the inspector for one of your script assets?
Ideally that "GameObe" one that's cut off in the screenshot
this is the information I'm looking for
okay, good, it's in the default Assembly-CSharp.dll assembly
If it wasn't, you would need to go and configure an asmdef somewhere
I haven't got any other great ideas right now -- I would delete the Library folder and let everything reimport
- it's time
ol' reliable
Although I'd expect to see a ton of compile errors from the GLTFast package's scripts if there were something wrong
the GLTF does seem to work
If I manually export
Everything seems to work besides exporting via script since I can't reference it
Thank you so much for the help @heady iris, I really appreciate it ❤️
no prob! hope you get it fixed (:
You can just try to copy it and paste it later or save it as a prefab 🤔
dictionaries aren't serializable by unity
https://docs.unity3d.com/2020.1/Documentation/ScriptReference/ScriptableSingleton_1.html survives domain reloads, but the data needs to be serializable
Some workarounds though 🤔
You could use ISerializationCallbackHandler to turn that into a list and store it in a serialized field on save
and then populate the dictionary on load
er
ISerializationCallbackReceiver
Or basically create your own dictionary with serializefields
in fact, that's the exact use case the doc page shows, haha
so, the moment that unity says it's going to serialize you, you stuff your dictionary keys and values into lists, which unity can understand
and then right after it deserializes you, you put them back in the dictionary
there's your killer Unity 6 feature: making Dictionary<K,V> serializable..
Oof that would be great
I don't care about AI, but these type of things
I always recommend to have a camera holder/controller and the camera as a child within
Yeah a parent
Sometimes you get odd results when you change things in the camera transform
Damn, i could of save time and do something else than a dict.
Ill do nested struct
Apply it to the parent and add the collider
Was my idea before going for dicts
Cameras don't often have a collider. Normally your character or something does
Where the camera is just positioned at a point
Ty, ill try
The camera must not have it's own physics/gravity
But damn i got nested dictionaries
Hmm not sure, if the floor has a collider its a bit odd
Does it start above the ground?
@heady iris Yeah I'm out of ideas as well, odd issue
Even a clean project with just texmeshpro and GLTFast won't run it
And when I manually add it in a clean project, same thing happens
It's an error in the glt package
What editor version are you on? It worked fine for me in a 2022 LTS project
2021.3.14 LTS
wait, there it is!
i restarted the editor and now it's complaining that's a bogus namespace
VSCode is still happy
I'm surprised that you can just call the using GLTFast.Export; without manually adding the packages
oh, no, I installed that
Yes, that's all fine. That was caused by your asmdef reference asset
the asmdef reference asset was not relevant -- i explained what it does here
you wouldn't be adding your scripts to the GLTFast.Export assembly
that's what an asmdef reference does
It looks like Unity believes that GLTFast exists, but isn't aware of GLTFast.Export
Yeah, I have the same
i'm going to install something to look at what assemblies are being compiled
Okay, so this one is definitely not marked as auto-referenced now. I can't remember if I checked it last time.
I was definitely able to compile with using GLTFast.Export; up top, though
yeah, it's in a package
I don't understand why it went from working to broken on my end. That's very funky.
So here's what you can do to get around this:
Copy the package from Library/PackageCache/ to Packages/. This embeds the package in your project
so if it was Library/PackageCache/com.foo.bar@1.0/, you'd copy that to Packages/com.foo.bar@1.0/
The package contents will still appear in Packages/, but will no longer be read-only
Tick "Auto Referenced" on that assembly definition
It will now be automatically visible to the default assemblies (into which all of your code is currently going)
(without making VSCode complain, either)
Hey, how can i install Newtonsoft.Json? i installed it in a certain way and it doesn't compile when i try to use it what is the right way?
and what was this "certain way"?
add with git url com.unity.nuget.newtonsoft-json
that is not a git url. do you mean you added it by name?
i tried both
my editor
close the code editor, regenerate project files from the External Tools window, and reopen the code editor
what is the External Tools window?
it works thanks !
//Works fine
void SingleRotation()
{
Vector3 angles = GetAnglesFromCurve();
transform.rotation = Quaternion.Euler(angles.x, angles.y, angles.z) * initialRotation;
transform.position += currentSpeed * Time.fixedDeltaTime * transform.forward;
}```
```cs
//Doesn't work too well
void BlendedRotation()
{
Vector3 angles = GetAnglesFromCurve();
Quaternion curveRotation = Quaternion.Euler(angles.x, angles.y, angles.z) * initialRotation;
Vector3 targetDirection = (target.transform.position - transform.position).normalized;
Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up);
Quaternion extraRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, speed * Time.fixedDeltaTime); //been trying both Slerp and RotateTowards
transform.rotation = curveRotation * extraRotation;
transform.position += currentSpeed * Time.fixedDeltaTime * transform.forward;
}```
So I'm having a problem with blending two rotations together for projectile movement. Basically I've a curve of angles that primarily drives the rotation of the projectiles, while my secondary rotation allows this projectile to home into a target that's nearby. Some examples would be a snaking projectile motion that slowly rotates towards its target, but stays consistent with its motion.
So, having these both independent work fine, it's just once I add them together does it start creating problems. I believe it may have to do with my initial rotation that I am using along with RotateTowards as I combine rotations.
😅🙈 oh well u are completely right - thank u!
Wow great workaround, didn't think of just dragging the package, but it really does make sense
Yo! Is it possible to show a variable in the inspector without the ability to modify it in the inspector. I know I can do that with Debug mode, but is it possible without it?
I recommend NaughtyAttributes:
https://dbrizov.github.io/na-docs/attributes/meta_attributes/read_only.html
Thanks for the answer! I don't like the idea of using a package for this, so I'm just gonna use debug mode instead, but it's useful to know thanks!
Where is this coming from? It is very helpful. brought up examples directly in VS. I do not have Copilot or Cody installed
correction.. *Could be very helpful. so far the examples are, .. pretty useless
Just looks like some GitHub feature. They're basically searching all of github for usages of UnityEngine.Transform.Rotate matching that signature
remember Microsoft owns GitHub so they have all that data.
indeed. Strange though, as that is the first time i am noticing that. But, i am notoriously myopic (amongst me, myself and I) when it comes to IDEs
I want to keep expanding this to Day, Week, Month. In general I know how I want to handle each. But is there a better pattern for this beyond a bunch of nested IFs?
what are you going to do with these events?
Is this the best pattern?
The 'game time' and the rate it passes will be central to everything from the players hunger growing, to weighting NPC AI (just two examples, but again many systems will want to know what time it is, when time has passed, etc. but specifically the imaginary 'in game time' not real life time)
So i thought events/actions was the way to go so basically the whole game had access to it
I also wanted to be able to speed up, slow down, and stop game time independent of Unity's time scale
Yeah but typically this should be just based on a "Tick" system
individual minutes/seconds/hours generally wouldn't be that relevant
I had book marked something about tick systems recently, I'll dive into that and see what I come up with.
If I build a tick system, I would then be able to use it to advance any kind of in game time tracking I want right?
yes
I guess I'm curious though what would happen in the "OnHourChange" event, for example
I was thinking about that too... I probably only really need OnMinuteChange and then whoever is listening can decide based on what time it is if they want to do their event.
I was just sort of building everything + the kitchen sink for this prototype
In this tick system, would it make sense to still use actions? For instance, have my ticker class shout it's 'onTick' event, and have my World Clock class listen for that and update the clock onTick?
I think the world clock should be the thing responsible for the ticks
I was wondering if you might say that, as I'm looking at some people's tick classes they look like they're doing very similar things
something like:
public class WorldTimer : MonoBehaviour {
public const float TickDuration = 1f / 50f; // how long is a tick in seconds?
public long CurrentTicks { get; private set; }
public delegate void TickHandler(long currentTicks);
public event Tickhandler OnTick;
float _timer = 0;
void Update() {
_timer += Time.deltaTime;
while (_timer >= TickDuration) {
_timer -= TickDuration;
CurrentTicks += 1;
OnTick(CurrentTicks);
}
}
}```
This is how I've done stuff like this in the past
also make it a singleton usually
This is exactly how I do it as well. Usually a singleton TimeManager too.
Ah yeah, not entirely unlike where I was going. Can I ask, what's the design benefit of using a delegate for the TickHandler. What scenario might keeping the current ticks be useful?
Would someone listening to it just keep the current tick when they check 1 time
and then compare it next time they check?
Until they meet the goal they're looking for?
You could implement your MinuteHandler easily as like:
const long numberOfTicksPerMinute = (long)(3600 / TickDuration)
void MinuteChangeDetector(long currentTicks) {
if (currentTicks % numberOfTicksPerMinute == 0) {
Minutes++;
OnMinuteChanged?.Invoke(Minutes);
}
}```
it's very convenient to have the ticks in the delegate for lots of cases
Alright. This helps a lot. I know my homework now.
hi! currently trying to debug an input related issue for our mobile game, that only appears in built versions of the game. attaching visual studio to an android device hooked up via USB leads to the game booting with a black screen. opening up the APK without a debugger attatched leads to the game booting like normal. Any ideas what could be causing this, or alternative ways to debug our issue?
the black screen occurs after the splash art logos have played, and we couldn't figure out anything using logcat.
is your debugger pausing the game when you get the black screen?
You can also make a development build and use Debug.Log
the output shows loading modules like expected, all the dll's.
once they finish loading nothing happens though. doesn't seem to be paused either.
again, never been an issue before with any builds attatched via Unity Remote or even just plain USB (no debugger), only when using visual studio as a debugger.
didn't end up finding anything online about this either, if you need any more info lemme know.
Well I'd add a bunch of logging.
Add a SceneManager.sceneLoaded listener. Print the loaded scene name
Add a bunch of these at each of the phases. See how far it's getting:
https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
we'll try this and see what we find, thanks
refactoring when you violated the single responsibility principle is suck
i’m just going through my level editor code, which has 5 responsibilities. breaking it up is so painful
i wish i could visualize my dependencies better to break everything up
Seems tough, what kinda game are you making?
Maybe you could try a UML diagram, it may be a little bit of a bad habit but I find it helpful to split every part into a "state machine" to help see how the parts can be broken up, with a Init function and then whatever else that specific part needs, later on once you know how you want to split it up, you can probably merge some of the "states" into just functions or another form