Can GKObstacleGraph be saved to a file and loaded from there ? I cant find anything on this.
I would love to save and load precalculated graphs for my levels.
I have tried so far
NSArray * obstacles = [SKNode obstaclesFromNodePhysicsBodies:arrayOfBodies];
_graph = [GKObstacleGraph graphWithObstacles:obstacles bufferRadius:[(BaseUnit *)[_units firstObject] size].width/2];
[NSKeyedArchiver archiveRootObject:_graph toFile:@"/Users/roma/Desktop/myGraph.graph"];
But this is what I got:
-[GKObstacleGraph encodeWithCoder:]: unrecognized selector sent to instance 0x6180000432d0
GKObstacleGraph
is a subclass of GKGraph
, which (as of macOS 10.12, iOS 10, and tvOS 10) declares conformance to the NSCoding
protocol. That means you can serialize one to data or a file (and deserialize to create an instance from a file) using NSKeyedArchiver
(and NSKeyedUnarchiver) just like you can for any other object that supports NSCoding
.
For general info on archiving (which applies to any NSCoding
-compatible class), see Apple's Archives and Serializations Programming Guide.
Also, in Xcode 8 (when deploying to macOS 10.12, iOS 10, or tvOS 10), you can create GKGraph
s in a visual editor to go along with your SpriteKit scenes. When you do that, you use the GKScene class to load both the SpriteKit scene and the GK objects (which can include not just pathfinding graphs, but also entity/component info) from the .sks
file Xcode writes.
In older OS versions, the GKGraph
family doesn't support NSCoding
. However, all the information you need to reconstruct a GKObstacleGraph
is publicly accessible. So you could implement your own serialization by reading a graph's buffer radius and list of obstacles, and reading each obstacle's list of vertices. Write that info to a file however you like... then when you want to reconstruct a graph, create GKPolygonObstacle
s from the vertices you saved, and create a new GKObstacleGraph
from those obstacles and your saved buffer radius.